AINodeStorage.cpp 36 KB

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