AINodeStorage.cpp 32 KB

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