AINodeStorage.cpp 41 KB

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