AINodeStorage.cpp 37 KB

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