AINodeStorage.cpp 37 KB

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