AINodeStorage.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  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. for(int i = r.begin(); i != r.end(); i++)
  341. {
  342. auto & pos = tiles[i];
  343. for(auto layer : phisycalLayers)
  344. {
  345. auto chains = nodes.get(pos, layer);
  346. // fast cut inactive nodes
  347. if(chains[0].blocked())
  348. continue;
  349. existingChains.clear();
  350. newChains.clear();
  351. for(AIPathNode & node : chains)
  352. {
  353. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  354. existingChains.push_back(&node);
  355. }
  356. std::random_shuffle(existingChains.begin(), existingChains.end());
  357. for(AIPathNode * node : existingChains)
  358. {
  359. if(node->actor->isMovable)
  360. {
  361. calculateHeroChain(node, existingChains, newChains);
  362. }
  363. }
  364. for(auto delayed = delayedWork.begin(); delayed != delayedWork.end();)
  365. {
  366. auto newActor = delayed->carrier->actor->tryExchangeNoLock(delayed->other->actor);
  367. if(!newActor.lockAcquired) continue;
  368. if(newActor.actor)
  369. {
  370. newChains.push_back(calculateExchange(newActor.actor, delayed->carrier, delayed->other));
  371. }
  372. delayed++;
  373. }
  374. delayedWork.clear();
  375. cleanupInefectiveChains(newChains);
  376. addHeroChain(newChains);
  377. }
  378. }
  379. }
  380. void calculateHeroChain(
  381. AIPathNode * srcNode,
  382. const std::vector<AIPathNode *> & variants,
  383. std::vector<ExchangeCandidate> & result);
  384. void calculateHeroChain(
  385. AIPathNode * carrier,
  386. AIPathNode * other,
  387. std::vector<ExchangeCandidate> & result);
  388. void cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const;
  389. void addHeroChain(const std::vector<ExchangeCandidate> & result);
  390. ExchangeCandidate calculateExchange(
  391. ChainActor * exchangeActor,
  392. AIPathNode * carrierParentNode,
  393. AIPathNode * otherParentNode) const;
  394. void flushResult(std::vector<CGPathNode *> & result)
  395. {
  396. vstd::concatenate(result, heroChain);
  397. }
  398. };
  399. bool AINodeStorage::calculateHeroChain()
  400. {
  401. heroChainPass = EHeroChainPass::CHAIN;
  402. heroChain.clear();
  403. std::vector<int3> data(commitedTiles.begin(), commitedTiles.end());
  404. if(data.size() > 100)
  405. {
  406. boost::mutex resultMutex;
  407. std::random_shuffle(data.begin(), data.end());
  408. parallel_for(blocked_range<size_t>(0, data.size()), [&](const blocked_range<size_t>& r)
  409. {
  410. //auto r = blocked_range<size_t>(0, data.size());
  411. HeroChainCalculationTask task(*this, nodes, data, chainMask, heroChainTurn);
  412. task.execute(r);
  413. {
  414. boost::lock_guard<boost::mutex> resultLock(resultMutex);
  415. task.flushResult(heroChain);
  416. }
  417. });
  418. }
  419. else
  420. {
  421. auto r = blocked_range<size_t>(0, data.size());
  422. HeroChainCalculationTask task(*this, nodes, data, chainMask, heroChainTurn);
  423. task.execute(r);
  424. task.flushResult(heroChain);
  425. }
  426. commitedTiles.clear();
  427. return !heroChain.empty();
  428. }
  429. bool AINodeStorage::selectFirstActor()
  430. {
  431. if(actors.empty())
  432. return false;
  433. auto strongest = *vstd::maxElementByFun(actors, [](std::shared_ptr<ChainActor> actor) -> uint64_t
  434. {
  435. return actor->armyValue;
  436. });
  437. chainMask = strongest->chainMask;
  438. commitedTilesInitial = commitedTiles;
  439. return true;
  440. }
  441. bool AINodeStorage::selectNextActor()
  442. {
  443. auto currentActor = std::find_if(actors.begin(), actors.end(), [&](std::shared_ptr<ChainActor> actor)-> bool
  444. {
  445. return actor->chainMask == chainMask;
  446. });
  447. auto nextActor = actors.end();
  448. for(auto actor = actors.begin(); actor != actors.end(); actor++)
  449. {
  450. if(actor->get()->armyValue > currentActor->get()->armyValue
  451. || (actor->get()->armyValue == currentActor->get()->armyValue && actor <= currentActor))
  452. {
  453. continue;
  454. }
  455. if(nextActor == actors.end()
  456. || actor->get()->armyValue > nextActor->get()->armyValue)
  457. {
  458. nextActor = actor;
  459. }
  460. }
  461. if(nextActor != actors.end())
  462. {
  463. if(nextActor->get()->armyValue < MIN_ARMY_STRENGTH_FOR_NEXT_ACTOR)
  464. return false;
  465. chainMask = nextActor->get()->chainMask;
  466. commitedTiles = commitedTilesInitial;
  467. return true;
  468. }
  469. return false;
  470. }
  471. void HeroChainCalculationTask::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  472. {
  473. vstd::erase_if(result, [&](const ExchangeCandidate & chainInfo) -> bool
  474. {
  475. auto pos = chainInfo.coord;
  476. auto chains = nodes.get(pos, EPathfindingLayer::LAND);
  477. auto isNotEffective = storage.hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  478. || storage.hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  479. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  480. if(isNotEffective)
  481. {
  482. logAi->trace(
  483. "Skip exchange %s[%x] -> %s[%x] at %s is ineficient",
  484. chainInfo.otherParent->actor->toString(),
  485. chainInfo.otherParent->actor->chainMask,
  486. chainInfo.carrierParent->actor->toString(),
  487. chainInfo.carrierParent->actor->chainMask,
  488. chainInfo.carrierParent->coord.toString());
  489. }
  490. #endif
  491. return isNotEffective;
  492. });
  493. }
  494. void HeroChainCalculationTask::calculateHeroChain(
  495. AIPathNode * srcNode,
  496. const std::vector<AIPathNode *> & variants,
  497. std::vector<ExchangeCandidate> & result)
  498. {
  499. for(AIPathNode * node : variants)
  500. {
  501. if(node == srcNode || !node->actor)
  502. continue;
  503. if((node->actor->chainMask & chainMask) == 0 && (srcNode->actor->chainMask & chainMask) == 0)
  504. continue;
  505. if(node->actor->actorExchangeCount + srcNode->actor->actorExchangeCount > CHAIN_MAX_DEPTH)
  506. continue;
  507. if(node->action == CGPathNode::ENodeAction::BATTLE
  508. || node->action == CGPathNode::ENodeAction::TELEPORT_BATTLE
  509. || node->action == CGPathNode::ENodeAction::TELEPORT_NORMAL
  510. || node->action == CGPathNode::ENodeAction::TELEPORT_BLOCKING_VISIT)
  511. {
  512. continue;
  513. }
  514. if(node->turns > heroChainTurn
  515. || (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  516. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  517. {
  518. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  519. logAi->trace(
  520. "Skip exchange %s[%x] -> %s[%x] at %s because of %s",
  521. node->actor->toString(),
  522. node->actor->chainMask,
  523. srcNode->actor->toString(),
  524. srcNode->actor->chainMask,
  525. srcNode->coord.toString(),
  526. (node->turns > heroChainTurn
  527. ? "turn limit"
  528. : (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  529. ? "action unknown"
  530. : "chain mask"));
  531. #endif
  532. continue;
  533. }
  534. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  535. logAi->trace(
  536. "Thy exchange %s[%x] -> %s[%x] at %s",
  537. node->actor->toString(),
  538. node->actor->chainMask,
  539. srcNode->actor->toString(),
  540. srcNode->actor->chainMask,
  541. srcNode->coord.toString());
  542. #endif
  543. calculateHeroChain(srcNode, node, result);
  544. }
  545. }
  546. void HeroChainCalculationTask::calculateHeroChain(
  547. AIPathNode * carrier,
  548. AIPathNode * other,
  549. std::vector<ExchangeCandidate> & result)
  550. {
  551. if(carrier->armyLoss < carrier->actor->armyValue
  552. && (carrier->action != CGPathNode::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
  553. && carrier->action != CGPathNode::BLOCKING_VISIT
  554. && (other->armyLoss == 0 || other->armyLoss < other->actor->armyValue))
  555. {
  556. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  557. logAi->trace(
  558. "Exchange allowed %s[%x] -> %s[%x] at %s",
  559. other->actor->toString(),
  560. other->actor->chainMask,
  561. carrier->actor->toString(),
  562. carrier->actor->chainMask,
  563. carrier->coord.toString());
  564. #endif
  565. if(other->actor->isMovable)
  566. {
  567. bool hasLessMp = carrier->turns > other->turns || (carrier->turns == other->turns && carrier->moveRemains < other->moveRemains);
  568. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  569. if(hasLessMp && hasLessExperience)
  570. {
  571. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  572. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  573. #endif
  574. return;
  575. }
  576. }
  577. auto newActor = carrier->actor->tryExchangeNoLock(other->actor);
  578. if(!newActor.lockAcquired) delayedWork.push_back(DelayedWork(carrier, other));
  579. if(newActor.actor) result.push_back(calculateExchange(newActor.actor, carrier, other));
  580. }
  581. }
  582. void HeroChainCalculationTask::addHeroChain(const std::vector<ExchangeCandidate> & result)
  583. {
  584. for(const ExchangeCandidate & chainInfo : result)
  585. {
  586. auto carrier = chainInfo.carrierParent;
  587. auto newActor = chainInfo.actor;
  588. auto other = chainInfo.otherParent;
  589. auto chainNodeOptional = storage.getOrCreateNode(carrier->coord, carrier->layer, newActor);
  590. if(!chainNodeOptional)
  591. {
  592. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  593. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  594. #endif
  595. continue;
  596. }
  597. auto exchangeNode = chainNodeOptional.get();
  598. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  599. {
  600. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  601. logAi->trace(
  602. "Skip exchange %s[%x] -> %s[%x] at %s because node is in use",
  603. other->actor->toString(),
  604. other->actor->chainMask,
  605. carrier->actor->toString(),
  606. carrier->actor->chainMask,
  607. carrier->coord.toString());
  608. #endif
  609. continue;
  610. }
  611. if(exchangeNode->turns != 0xFF && exchangeNode->getCost() < chainInfo.getCost())
  612. {
  613. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  614. logAi->trace(
  615. "Skip exchange %s[%x] -> %s[%x] at %s because not effective enough. %f < %f",
  616. other->actor->toString(),
  617. other->actor->chainMask,
  618. carrier->actor->toString(),
  619. carrier->actor->chainMask,
  620. carrier->coord.toString(),
  621. exchangeNode->getCost(),
  622. chainInfo.getCost());
  623. #endif
  624. continue;
  625. }
  626. storage.commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.getCost());
  627. if(carrier->specialAction || carrier->chainOther)
  628. {
  629. // there is some action on source tile which should be performed before we can bypass it
  630. exchangeNode->theNodeBefore = carrier;
  631. }
  632. if(exchangeNode->actor->actorAction)
  633. {
  634. exchangeNode->theNodeBefore = carrier;
  635. exchangeNode->specialAction = exchangeNode->actor->actorAction;
  636. }
  637. exchangeNode->chainOther = other;
  638. exchangeNode->armyLoss = chainInfo.armyLoss;
  639. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  640. logAi->trace(
  641. "Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
  642. exchangeNode->coord.toString(),
  643. other->actor->toString(),
  644. exchangeNode->actor->toString(),
  645. exchangeNode->actor->chainMask,
  646. exchangeNode->getCost(),
  647. std::to_string(exchangeNode->turns),
  648. exchangeNode->moveRemains,
  649. exchangeNode->actor->armyValue);
  650. #endif
  651. heroChain.push_back(exchangeNode);
  652. }
  653. }
  654. ExchangeCandidate HeroChainCalculationTask::calculateExchange(
  655. ChainActor * exchangeActor,
  656. AIPathNode * carrierParentNode,
  657. AIPathNode * otherParentNode) const
  658. {
  659. ExchangeCandidate candidate;
  660. candidate.layer = carrierParentNode->layer;
  661. candidate.coord = carrierParentNode->coord;
  662. candidate.carrierParent = carrierParentNode;
  663. candidate.otherParent = otherParentNode;
  664. candidate.actor = exchangeActor;
  665. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  666. candidate.turns = carrierParentNode->turns;
  667. candidate.setCost(carrierParentNode->getCost() + otherParentNode->getCost() / 1000.0);
  668. candidate.moveRemains = carrierParentNode->moveRemains;
  669. if(carrierParentNode->turns < otherParentNode->turns)
  670. {
  671. int moveRemains = exchangeActor->maxMovePoints(carrierParentNode->layer);
  672. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  673. + carrierParentNode->moveRemains / (float)moveRemains;
  674. candidate.turns = otherParentNode->turns;
  675. candidate.setCost(candidate.getCost() + waitingCost);
  676. candidate.moveRemains = moveRemains;
  677. }
  678. return candidate;
  679. }
  680. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  681. {
  682. std::set<const CGHeroInstance *> heroes;
  683. for(auto actor : actors)
  684. {
  685. if(actor->hero)
  686. heroes.insert(actor->hero);
  687. }
  688. return heroes;
  689. }
  690. bool AINodeStorage::isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  691. {
  692. if(heroChainPass == EHeroChainPass::CHAIN && destination.node->turns > heroChainTurn)
  693. {
  694. return true;
  695. }
  696. auto aiNode = getAINode(destination.node);
  697. if(heroChainPass != EHeroChainPass::CHAIN
  698. && destination.node->turns > turnDistanceLimit[aiNode->actor->heroRole])
  699. {
  700. return true;
  701. }
  702. return false;
  703. }
  704. void AINodeStorage::setHeroes(std::map<const CGHeroInstance *, HeroRole> heroes)
  705. {
  706. playerID = ai->playerID;
  707. for(auto & hero : heroes)
  708. {
  709. uint64_t mask = FirstActorMask << actors.size();
  710. auto actor = std::make_shared<HeroActor>(hero.first, hero.second, mask, ai);
  711. if(actor->hero->tempOwner != ai->playerID)
  712. {
  713. bool onLand = !actor->hero->boat;
  714. actor->initialMovement = actor->hero->maxMovePoints(onLand);
  715. }
  716. playerID = actor->hero->tempOwner;
  717. actors.push_back(actor);
  718. }
  719. }
  720. void AINodeStorage::setTownsAndDwellings(
  721. const std::vector<const CGTownInstance *> & towns,
  722. const std::set<const CGObjectInstance *> & visitableObjs)
  723. {
  724. for(auto town : towns)
  725. {
  726. uint64_t mask = FirstActorMask << actors.size();
  727. // TODO: investigate logix of second condition || ai->nullkiller->getHeroLockedReason(town->garrisonHero) != HeroLockedReason::DEFENCE
  728. // check defence imrove
  729. if(!town->garrisonHero)
  730. {
  731. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  732. }
  733. }
  734. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  735. auto waitForGrowth = dayOfWeek > 4;*/
  736. for(auto obj: visitableObjs)
  737. {
  738. if(obj->ID == Obj::HILL_FORT)
  739. {
  740. uint64_t mask = FirstActorMask << actors.size();
  741. actors.push_back(std::make_shared<HillFortActor>(obj, mask));
  742. }
  743. /*const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  744. if(dwelling)
  745. {
  746. uint64_t mask = 1 << actors.size();
  747. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  748. if(dwellingActor->creatureSet->getArmyStrength())
  749. {
  750. actors.push_back(dwellingActor);
  751. }
  752. if(waitForGrowth)
  753. {
  754. mask = 1 << actors.size();
  755. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  756. if(dwellingActor->creatureSet->getArmyStrength())
  757. {
  758. actors.push_back(dwellingActor);
  759. }
  760. }
  761. }*/
  762. }
  763. }
  764. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  765. const PathNodeInfo & source,
  766. const PathfinderConfig * pathfinderConfig,
  767. const CPathfinderHelper * pathfinderHelper)
  768. {
  769. std::vector<CGPathNode *> neighbours;
  770. if(source.isNodeObjectVisitable())
  771. {
  772. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  773. auto srcNode = getAINode(source.node);
  774. for(auto & neighbour : accessibleExits)
  775. {
  776. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  777. if(!node)
  778. continue;
  779. neighbours.push_back(node.get());
  780. }
  781. }
  782. return neighbours;
  783. }
  784. struct TowmPortalFinder
  785. {
  786. const std::vector<CGPathNode *> & initialNodes;
  787. SecSkillLevel::SecSkillLevel townPortalSkillLevel;
  788. uint64_t movementNeeded;
  789. const ChainActor * actor;
  790. const CGHeroInstance * hero;
  791. std::vector<const CGTownInstance *> targetTowns;
  792. AINodeStorage * nodeStorage;
  793. SpellID spellID;
  794. const CSpell * townPortal;
  795. TowmPortalFinder(
  796. const ChainActor * actor,
  797. const std::vector<CGPathNode *> & initialNodes,
  798. std::vector<const CGTownInstance *> targetTowns,
  799. AINodeStorage * nodeStorage)
  800. :actor(actor), initialNodes(initialNodes), hero(actor->hero),
  801. targetTowns(targetTowns), nodeStorage(nodeStorage)
  802. {
  803. spellID = SpellID::TOWN_PORTAL;
  804. townPortal = spellID.toSpell();
  805. // TODO: Copy/Paste from TownPortalMechanics
  806. townPortalSkillLevel = SecSkillLevel::SecSkillLevel(hero->getSpellSchoolLevel(townPortal));
  807. movementNeeded = GameConstants::BASE_MOVEMENT_COST * (townPortalSkillLevel >= SecSkillLevel::EXPERT ? 2 : 3);
  808. }
  809. bool actorCanCastTownPortal()
  810. {
  811. return hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal);
  812. }
  813. CGPathNode * getBestInitialNodeForTownPortal(const CGTownInstance * targetTown)
  814. {
  815. for(CGPathNode * node : initialNodes)
  816. {
  817. auto aiNode = nodeStorage->getAINode(node);
  818. if(aiNode->actor->baseActor != actor
  819. || node->layer != EPathfindingLayer::LAND
  820. || node->moveRemains < movementNeeded)
  821. {
  822. continue;
  823. }
  824. if(townPortalSkillLevel < SecSkillLevel::ADVANCED)
  825. {
  826. const CGTownInstance * nearestTown = *vstd::minElementByFun(targetTowns, [&](const CGTownInstance * t) -> int
  827. {
  828. return node->coord.dist2dSQ(t->visitablePos());
  829. });
  830. if(targetTown != nearestTown)
  831. continue;
  832. }
  833. return node;
  834. }
  835. return nullptr;
  836. }
  837. boost::optional<AIPathNode *> createTownPortalNode(const CGTownInstance * targetTown)
  838. {
  839. auto bestNode = getBestInitialNodeForTownPortal(targetTown);
  840. if(!bestNode)
  841. return boost::none;
  842. auto nodeOptional = nodeStorage->getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, actor->castActor);
  843. if(!nodeOptional)
  844. return boost::none;
  845. AIPathNode * node = nodeOptional.get();
  846. float movementCost = (float)movementNeeded / (float)hero->maxMovePoints(EPathfindingLayer::LAND);
  847. movementCost += bestNode->getCost();
  848. if(node->action == CGPathNode::UNKNOWN || node->getCost() > movementCost)
  849. {
  850. nodeStorage->commit(
  851. node,
  852. nodeStorage->getAINode(bestNode),
  853. CGPathNode::TELEPORT_NORMAL,
  854. bestNode->turns,
  855. bestNode->moveRemains - movementNeeded,
  856. movementCost);
  857. node->theNodeBefore = bestNode;
  858. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  859. }
  860. return nodeOptional;
  861. }
  862. };
  863. template<class TVector>
  864. void AINodeStorage::calculateTownPortal(
  865. const ChainActor * actor,
  866. const std::map<const CGHeroInstance *, int> & maskMap,
  867. const std::vector<CGPathNode *> & initialNodes,
  868. TVector & output)
  869. {
  870. auto towns = cb->getTownsInfo(false);
  871. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  872. {
  873. return cb->getPlayerRelations(actor->hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  874. });
  875. if(!towns.size())
  876. {
  877. return; // no towns no need to run loop further
  878. }
  879. TowmPortalFinder townPortalFinder(actor, initialNodes, towns, this);
  880. if(townPortalFinder.actorCanCastTownPortal())
  881. {
  882. for(const CGTownInstance * targetTown : towns)
  883. {
  884. // TODO: allow to hide visiting hero in garrison
  885. if(targetTown->visitingHero && maskMap.find(targetTown->visitingHero.get()) != maskMap.end())
  886. {
  887. auto basicMask = maskMap.at(targetTown->visitingHero.get());
  888. bool heroIsInChain = (actor->chainMask & basicMask) != 0;
  889. bool sameActorInTown = actor->chainMask == basicMask;
  890. if(sameActorInTown || !heroIsInChain)
  891. continue;
  892. }
  893. auto nodeOptional = townPortalFinder.createTownPortalNode(targetTown);
  894. if(nodeOptional)
  895. {
  896. #if NKAI_PATHFINDER_TRACE_LEVEL >= 1
  897. logAi->trace("Adding town portal node at %s", targetTown->name);
  898. #endif
  899. output.push_back(nodeOptional.get());
  900. }
  901. }
  902. }
  903. }
  904. void AINodeStorage::calculateTownPortalTeleportations(std::vector<CGPathNode *> & initialNodes)
  905. {
  906. std::set<const ChainActor *> actorsOfInitial;
  907. for(const CGPathNode * node : initialNodes)
  908. {
  909. auto aiNode = getAINode(node);
  910. if(aiNode->actor->hero)
  911. actorsOfInitial.insert(aiNode->actor->baseActor);
  912. }
  913. std::map<const CGHeroInstance *, int> maskMap;
  914. for(std::shared_ptr<ChainActor> basicActor : actors)
  915. {
  916. if(basicActor->hero)
  917. maskMap[basicActor->hero] = basicActor->chainMask;
  918. }
  919. boost::sort(initialNodes, NodeComparer<CGPathNode>());
  920. std::vector<const ChainActor *> actorsVector(actorsOfInitial.begin(), actorsOfInitial.end());
  921. tbb::concurrent_vector<CGPathNode *> output;
  922. if(actorsVector.size() * initialNodes.size() > 1000)
  923. {
  924. parallel_for(blocked_range<size_t>(0, actorsVector.size()), [&](const blocked_range<size_t> & r)
  925. {
  926. for(int i = r.begin(); i != r.end(); i++)
  927. {
  928. calculateTownPortal(actorsVector[i], maskMap, initialNodes, output);
  929. }
  930. });
  931. std::copy(output.begin(), output.end(), std::back_inserter(initialNodes));
  932. }
  933. else
  934. {
  935. for(auto actor : actorsVector)
  936. {
  937. calculateTownPortal(actor, maskMap, initialNodes, initialNodes);
  938. }
  939. }
  940. }
  941. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  942. {
  943. auto pos = destination.coord;
  944. auto chains = nodes.get(pos, EPathfindingLayer::LAND);
  945. return hasBetterChain(source.node, getAINode(destination.node), chains);
  946. }
  947. template<class NodeRange>
  948. bool AINodeStorage::hasBetterChain(
  949. const CGPathNode * source,
  950. const AIPathNode * candidateNode,
  951. const NodeRange & chains) const
  952. {
  953. auto candidateActor = candidateNode->actor;
  954. for(const AIPathNode & node : chains)
  955. {
  956. auto sameNode = node.actor == candidateNode->actor;
  957. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  958. {
  959. continue;
  960. }
  961. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  962. {
  963. if(node.getCost() < candidateNode->getCost())
  964. {
  965. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  966. logAi->trace(
  967. "Block ineficient battle move %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  968. source->coord.toString(),
  969. candidateNode->coord.toString(),
  970. candidateNode->actor->hero->name,
  971. candidateNode->actor->chainMask,
  972. candidateNode->actor->armyValue,
  973. node.moveRemains - candidateNode->moveRemains);
  974. #endif
  975. return true;
  976. }
  977. }
  978. if(candidateActor->chainMask != node.actor->chainMask && heroChainPass != EHeroChainPass::FINAL)
  979. continue;
  980. auto nodeActor = node.actor;
  981. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  982. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  983. if(nodeArmyValue > candidateArmyValue
  984. && node.getCost() <= candidateNode->getCost())
  985. {
  986. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  987. logAi->trace(
  988. "Block ineficient move because of stronger army %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  989. source->coord.toString(),
  990. candidateNode->coord.toString(),
  991. candidateNode->actor->hero->name,
  992. candidateNode->actor->chainMask,
  993. candidateNode->actor->armyValue,
  994. node.moveRemains - candidateNode->moveRemains);
  995. #endif
  996. return true;
  997. }
  998. if(heroChainPass == EHeroChainPass::FINAL)
  999. {
  1000. if(nodeArmyValue == candidateArmyValue
  1001. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  1002. && node.getCost() <= candidateNode->getCost())
  1003. {
  1004. if(nodeActor->heroFightingStrength == candidateActor->heroFightingStrength
  1005. && node.getCost() == candidateNode->getCost()
  1006. && &node < candidateNode)
  1007. {
  1008. continue;
  1009. }
  1010. #if NKAI_PATHFINDER_TRACE_LEVEL >= 2
  1011. logAi->trace(
  1012. "Block ineficient move because of stronger hero %s->%s, hero: %s[%X], army %lld, mp diff: %i",
  1013. source->coord.toString(),
  1014. candidateNode->coord.toString(),
  1015. candidateNode->actor->hero->name,
  1016. candidateNode->actor->chainMask,
  1017. candidateNode->actor->armyValue,
  1018. node.moveRemains - candidateNode->moveRemains);
  1019. #endif
  1020. return true;
  1021. }
  1022. }
  1023. }
  1024. return false;
  1025. }
  1026. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  1027. {
  1028. auto chains = nodes.get(pos, layer);
  1029. for(const AIPathNode & node : chains)
  1030. {
  1031. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  1032. && node.actor && node.actor->hero == hero.h)
  1033. {
  1034. return true;
  1035. }
  1036. }
  1037. return false;
  1038. }
  1039. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  1040. {
  1041. std::vector<AIPath> paths;
  1042. paths.reserve(AIPathfinding::NUM_CHAINS / 4);
  1043. auto chains = nodes.get(pos, isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL);
  1044. for(const AIPathNode & node : chains)
  1045. {
  1046. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  1047. {
  1048. continue;
  1049. }
  1050. AIPath path;
  1051. path.targetHero = node.actor->hero;
  1052. path.heroArmy = node.actor->creatureSet;
  1053. path.armyLoss = node.armyLoss;
  1054. path.targetObjectDanger = evaluateDanger(pos, path.targetHero, !node.actor->allowBattle);
  1055. path.targetObjectArmyLoss = evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  1056. path.chainMask = node.actor->chainMask;
  1057. path.exchangeCount = node.actor->actorExchangeCount;
  1058. fillChainInfo(&node, path, -1);
  1059. paths.push_back(path);
  1060. }
  1061. return paths;
  1062. }
  1063. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  1064. {
  1065. while(node != nullptr)
  1066. {
  1067. if(!node->actor->hero)
  1068. return;
  1069. if(node->chainOther)
  1070. fillChainInfo(node->chainOther, path, parentIndex);
  1071. //if(node->actor->hero->visitablePos() != node->coord)
  1072. {
  1073. AIPathNodeInfo pathNode;
  1074. pathNode.cost = node->getCost();
  1075. pathNode.targetHero = node->actor->hero;
  1076. pathNode.chainMask = node->actor->chainMask;
  1077. pathNode.specialAction = node->specialAction;
  1078. pathNode.turns = node->turns;
  1079. pathNode.danger = node->danger;
  1080. pathNode.coord = node->coord;
  1081. pathNode.parentIndex = parentIndex;
  1082. pathNode.actionIsBlocked = false;
  1083. if(pathNode.specialAction)
  1084. {
  1085. auto targetNode =node->theNodeBefore ? getAINode(node->theNodeBefore) : node;
  1086. pathNode.actionIsBlocked = !pathNode.specialAction->canAct(targetNode);
  1087. }
  1088. parentIndex = path.nodes.size();
  1089. path.nodes.push_back(pathNode);
  1090. }
  1091. node = getAINode(node->theNodeBefore);
  1092. }
  1093. }
  1094. AIPath::AIPath()
  1095. : nodes({})
  1096. {
  1097. }
  1098. std::shared_ptr<const SpecialAction> AIPath::getFirstBlockedAction() const
  1099. {
  1100. for(auto node = nodes.rbegin(); node != nodes.rend(); node++)
  1101. {
  1102. if(node->specialAction && node->actionIsBlocked)
  1103. return node->specialAction;
  1104. }
  1105. return std::shared_ptr<const SpecialAction>();
  1106. }
  1107. int3 AIPath::firstTileToGet() const
  1108. {
  1109. if(nodes.size())
  1110. {
  1111. return nodes.back().coord;
  1112. }
  1113. return int3(-1, -1, -1);
  1114. }
  1115. int3 AIPath::targetTile() const
  1116. {
  1117. if(nodes.size())
  1118. {
  1119. return targetNode().coord;
  1120. }
  1121. return int3(-1, -1, -1);
  1122. }
  1123. const AIPathNodeInfo & AIPath::firstNode() const
  1124. {
  1125. return nodes.back();
  1126. }
  1127. const AIPathNodeInfo & AIPath::targetNode() const
  1128. {
  1129. auto & node = nodes.front();
  1130. return targetHero == node.targetHero ? node : nodes.at(1);
  1131. }
  1132. uint64_t AIPath::getPathDanger() const
  1133. {
  1134. if(nodes.empty())
  1135. return 0;
  1136. return targetNode().danger;
  1137. }
  1138. float AIPath::movementCost() const
  1139. {
  1140. if(nodes.empty())
  1141. return 0.0f;
  1142. return targetNode().cost;
  1143. }
  1144. uint8_t AIPath::turn() const
  1145. {
  1146. if(nodes.empty())
  1147. return 0;
  1148. return targetNode().turns;
  1149. }
  1150. uint64_t AIPath::getHeroStrength() const
  1151. {
  1152. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  1153. }
  1154. uint64_t AIPath::getTotalDanger() const
  1155. {
  1156. uint64_t pathDanger = getPathDanger();
  1157. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  1158. return danger;
  1159. }
  1160. bool AIPath::containsHero(const CGHeroInstance * hero) const
  1161. {
  1162. if(targetHero == hero)
  1163. return true;
  1164. for(auto node : nodes)
  1165. {
  1166. if(node.targetHero == hero)
  1167. return true;
  1168. }
  1169. return false;
  1170. }
  1171. uint64_t AIPath::getTotalArmyLoss() const
  1172. {
  1173. return armyLoss + targetObjectArmyLoss;
  1174. }
  1175. std::string AIPath::toString() const
  1176. {
  1177. std::stringstream str;
  1178. str << targetHero->name << "[" << std::hex << chainMask << std::dec << "]" << ", turn " << (int)(turn()) << ": ";
  1179. for(auto node : nodes)
  1180. str << node.targetHero->name << "[" << std::hex << node.chainMask << std::dec << "]" << "->" << node.coord.toString() << "; ";
  1181. return str.str();
  1182. }
  1183. }