AINodeStorage.cpp 37 KB

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