AINodeStorage.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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. turnDistanceLimit[HeroRole::MAIN] = 255;
  98. turnDistanceLimit[HeroRole::SCOUT] = 255;
  99. }
  100. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  101. {
  102. return static_cast<const AIPathNode *>(node);
  103. }
  104. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  105. {
  106. auto aiNode = static_cast<AIPathNode *>(node);
  107. updater(aiNode);
  108. }
  109. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  110. const int3 & pos,
  111. const EPathfindingLayer layer,
  112. const ChainActor * actor)
  113. {
  114. int bucketIndex = ((uintptr_t)actor) % BUCKET_COUNT;
  115. int bucketOffset = bucketIndex * BUCKET_SIZE;
  116. auto chains = nodes.get(pos, layer);
  117. if(chains[0].blocked())
  118. {
  119. return boost::none;
  120. }
  121. for(auto i = BUCKET_SIZE - 1; i >= 0; i--)
  122. {
  123. AIPathNode & node = chains[i + bucketOffset];
  124. if(node.actor == actor)
  125. {
  126. return &node;
  127. }
  128. if(!node.actor)
  129. {
  130. node.actor = actor;
  131. return &node;
  132. }
  133. }
  134. return boost::none;
  135. }
  136. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  137. {
  138. if(heroChainPass)
  139. {
  140. calculateTownPortalTeleportations(heroChain);
  141. return heroChain;
  142. }
  143. std::vector<CGPathNode *> initialNodes;
  144. for(auto actorPtr : actors)
  145. {
  146. ChainActor * actor = actorPtr.get();
  147. AIPathNode * initialNode =
  148. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  149. .get();
  150. if(!initialNode)
  151. continue;
  152. initialNode->inPQ = false;
  153. initialNode->pq = nullptr;
  154. initialNode->turns = actor->initialTurn;
  155. initialNode->moveRemains = actor->initialMovement;
  156. initialNode->danger = 0;
  157. initialNode->cost = actor->initialTurn;
  158. initialNode->action = CGPathNode::ENodeAction::NORMAL;
  159. if(actor->isMovable)
  160. {
  161. initialNodes.push_back(initialNode);
  162. }
  163. else
  164. {
  165. initialNode->locked = true;
  166. }
  167. }
  168. calculateTownPortalTeleportations(initialNodes);
  169. return initialNodes;
  170. }
  171. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  172. {
  173. for(AIPathNode & heroNode : nodes.get(coord, layer))
  174. {
  175. heroNode.actor = nullptr;
  176. heroNode.danger = 0;
  177. heroNode.manaCost = 0;
  178. heroNode.specialAction.reset();
  179. heroNode.armyLoss = 0;
  180. heroNode.chainOther = nullptr;
  181. heroNode.update(coord, layer, accessibility);
  182. }
  183. }
  184. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  185. {
  186. const AIPathNode * srcNode = getAINode(source.node);
  187. updateAINode(destination.node, [&](AIPathNode * dstNode)
  188. {
  189. commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
  190. if(srcNode->specialAction || srcNode->chainOther)
  191. {
  192. // there is some action on source tile which should be performed before we can bypass it
  193. destination.node->theNodeBefore = source.node;
  194. }
  195. if(dstNode->specialAction && dstNode->actor)
  196. {
  197. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  198. }
  199. });
  200. }
  201. void AINodeStorage::commit(
  202. AIPathNode * destination,
  203. const AIPathNode * source,
  204. CGPathNode::ENodeAction action,
  205. int turn,
  206. int movementLeft,
  207. float cost) const
  208. {
  209. destination->action = action;
  210. destination->cost = cost;
  211. destination->moveRemains = movementLeft;
  212. destination->turns = turn;
  213. destination->armyLoss = source->armyLoss;
  214. destination->manaCost = source->manaCost;
  215. destination->danger = source->danger;
  216. destination->theNodeBefore = source->theNodeBefore;
  217. destination->chainOther = nullptr;
  218. #if PATHFINDER_TRACE_LEVEL >= 2
  219. logAi->trace(
  220. "Commited %s -> %s, cost: %f, turn: %s, mp: %d, hero: %s, mask: %x, army: %lld",
  221. source->coord.toString(),
  222. destination->coord.toString(),
  223. destination->getCost(),
  224. std::to_string(destination->turns),
  225. destination->moveRemains,
  226. destination->actor->toString(),
  227. destination->actor->chainMask,
  228. destination->actor->armyValue);
  229. #endif
  230. if(destination->turns <= heroChainTurn)
  231. {
  232. commitedTiles.insert(destination->coord);
  233. }
  234. }
  235. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  236. const PathNodeInfo & source,
  237. const PathfinderConfig * pathfinderConfig,
  238. const CPathfinderHelper * pathfinderHelper)
  239. {
  240. std::vector<CGPathNode *> neighbours;
  241. neighbours.reserve(16);
  242. const AIPathNode * srcNode = getAINode(source.node);
  243. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  244. for(auto & neighbour : accessibleNeighbourTiles)
  245. {
  246. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  247. {
  248. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  249. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  250. continue;
  251. neighbours.push_back(nextNode.get());
  252. }
  253. }
  254. return neighbours;
  255. }
  256. EPathfindingLayer phisycalLayers[2] = {EPathfindingLayer::LAND, EPathfindingLayer::SAIL};
  257. bool AINodeStorage::increaseHeroChainTurnLimit()
  258. {
  259. if(heroChainTurn >= heroChainMaxTurns)
  260. return false;
  261. heroChainTurn++;
  262. commitedTiles.clear();
  263. for(auto layer : phisycalLayers)
  264. {
  265. foreach_tile_pos([&](const int3 & pos)
  266. {
  267. auto chains = nodes.get(pos, layer);
  268. if(!chains[0].blocked())
  269. {
  270. for(AIPathNode & node : chains)
  271. {
  272. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  273. {
  274. commitedTiles.insert(pos);
  275. break;
  276. }
  277. }
  278. }
  279. });
  280. }
  281. return true;
  282. }
  283. bool AINodeStorage::calculateHeroChainFinal()
  284. {
  285. heroChainPass = EHeroChainPass::FINAL;
  286. heroChain.resize(0);
  287. for(auto layer : phisycalLayers)
  288. {
  289. foreach_tile_pos([&](const int3 & pos)
  290. {
  291. auto chains = nodes.get(pos, layer);
  292. if(!chains[0].blocked())
  293. {
  294. for(AIPathNode & node : chains)
  295. {
  296. if(node.turns > heroChainTurn
  297. && !node.locked
  298. && node.action != CGPathNode::ENodeAction::UNKNOWN
  299. && node.actor->actorExchangeCount > 1
  300. && !hasBetterChain(&node, &node, chains))
  301. {
  302. heroChain.push_back(&node);
  303. }
  304. }
  305. }
  306. });
  307. }
  308. return heroChain.size();
  309. }
  310. bool AINodeStorage::calculateHeroChain()
  311. {
  312. heroChainPass = EHeroChainPass::CHAIN;
  313. heroChain.resize(0);
  314. std::vector<AIPathNode *> existingChains;
  315. std::vector<ExchangeCandidate> newChains;
  316. existingChains.reserve(NUM_CHAINS);
  317. newChains.reserve(NUM_CHAINS);
  318. for(auto & pos : commitedTiles)
  319. {
  320. for(auto layer : phisycalLayers)
  321. {
  322. auto chains = nodes.get(pos, layer);
  323. // fast cut inactive nodes
  324. if(chains[0].blocked())
  325. continue;
  326. existingChains.clear();
  327. newChains.clear();
  328. for(AIPathNode & node : chains)
  329. {
  330. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  331. existingChains.push_back(&node);
  332. }
  333. for(AIPathNode * node : existingChains)
  334. {
  335. if(node->actor->isMovable)
  336. {
  337. calculateHeroChain(node, existingChains, newChains);
  338. }
  339. }
  340. cleanupInefectiveChains(newChains);
  341. addHeroChain(newChains);
  342. }
  343. }
  344. commitedTiles.clear();
  345. return heroChain.size();
  346. }
  347. bool AINodeStorage::selectFirstActor()
  348. {
  349. if(!actors.size())
  350. return false;
  351. auto strongest = *vstd::maxElementByFun(actors, [](std::shared_ptr<ChainActor> actor) -> uint64_t
  352. {
  353. return actor->armyValue;
  354. });
  355. chainMask = strongest->chainMask;
  356. commitedTilesInitial = commitedTiles;
  357. return true;
  358. }
  359. bool AINodeStorage::selectNextActor()
  360. {
  361. auto currentActor = std::find_if(actors.begin(), actors.end(), [&](std::shared_ptr<ChainActor> actor)-> bool
  362. {
  363. return actor->chainMask == chainMask;
  364. });
  365. auto nextActor = actors.end();
  366. for(auto actor = actors.begin(); actor != actors.end(); actor++)
  367. {
  368. if(actor->get()->armyValue > currentActor->get()->armyValue
  369. || actor->get()->armyValue == currentActor->get()->armyValue && actor <= currentActor)
  370. {
  371. continue;
  372. }
  373. if(nextActor == actors.end()
  374. || actor->get()->armyValue > nextActor->get()->armyValue)
  375. {
  376. nextActor = actor;
  377. }
  378. }
  379. if(nextActor != actors.end())
  380. {
  381. chainMask = nextActor->get()->chainMask;
  382. commitedTiles = commitedTilesInitial;
  383. return true;
  384. }
  385. return false;
  386. }
  387. void AINodeStorage::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  388. {
  389. vstd::erase_if(result, [&](const ExchangeCandidate & chainInfo) -> bool
  390. {
  391. auto pos = chainInfo.coord;
  392. auto chains = nodes.get(pos, EPathfindingLayer::LAND);
  393. return hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  394. || hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  395. });
  396. }
  397. void AINodeStorage::calculateHeroChain(
  398. AIPathNode * srcNode,
  399. const std::vector<AIPathNode *> & variants,
  400. std::vector<ExchangeCandidate> & result) const
  401. {
  402. for(AIPathNode * node : variants)
  403. {
  404. if(node == srcNode || !node->actor)
  405. continue;
  406. if((node->actor->chainMask & chainMask) == 0 && (srcNode->actor->chainMask & chainMask) == 0)
  407. continue;
  408. if(node->action == CGPathNode::ENodeAction::BATTLE
  409. || node->action == CGPathNode::ENodeAction::TELEPORT_BATTLE
  410. || node->action == CGPathNode::ENodeAction::TELEPORT_NORMAL
  411. || node->action == CGPathNode::ENodeAction::TELEPORT_BLOCKING_VISIT)
  412. {
  413. continue;
  414. }
  415. if(node->turns > heroChainTurn
  416. || (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  417. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  418. {
  419. #if PATHFINDER_TRACE_LEVEL >= 2
  420. logAi->trace(
  421. "Skip exchange %s[%x] -> %s[%x] at %s because of %s",
  422. node->actor->toString(),
  423. node->actor->chainMask,
  424. srcNode->actor->toString(),
  425. srcNode->actor->chainMask,
  426. srcNode->coord.toString(),
  427. (node->turns > heroChainTurn
  428. ? "turn limit"
  429. : (node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero)
  430. ? "action unknown"
  431. : "chain mask"));
  432. #endif
  433. continue;
  434. }
  435. #if PATHFINDER_TRACE_LEVEL >= 2
  436. logAi->trace(
  437. "Thy exchange %s[%x] -> %s[%x] at %s",
  438. node->actor->toString(),
  439. node->actor->chainMask,
  440. srcNode->actor->toString(),
  441. srcNode->actor->chainMask,
  442. srcNode->coord.toString());
  443. #endif
  444. calculateHeroChain(srcNode, node, result);
  445. }
  446. }
  447. void AINodeStorage::calculateHeroChain(
  448. AIPathNode * carrier,
  449. AIPathNode * other,
  450. std::vector<ExchangeCandidate> & result) const
  451. {
  452. if(carrier->armyLoss < carrier->actor->armyValue
  453. && (carrier->action != CGPathNode::BATTLE || (carrier->actor->allowBattle && carrier->specialAction))
  454. && carrier->action != CGPathNode::BLOCKING_VISIT
  455. && (other->armyLoss == 0 || other->armyLoss < other->actor->armyValue)
  456. && carrier->actor->canExchange(other->actor))
  457. {
  458. #if PATHFINDER_TRACE_LEVEL >= 2
  459. logAi->trace(
  460. "Exchange allowed %s[%x] -> %s[%x] at %s",
  461. other->actor->toString(),
  462. other->actor->chainMask,
  463. carrier->actor->toString(),
  464. carrier->actor->chainMask,
  465. carrier->coord.toString());
  466. #endif
  467. if(other->actor->isMovable)
  468. {
  469. bool hasLessMp = carrier->turns > other->turns || (carrier->turns == other->turns && carrier->moveRemains < other->moveRemains);
  470. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  471. if(hasLessMp && hasLessExperience)
  472. {
  473. #if PATHFINDER_TRACE_LEVEL >= 2
  474. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  475. #endif
  476. return;
  477. }
  478. }
  479. auto newActor = carrier->actor->exchange(other->actor);
  480. result.push_back(calculateExchange(newActor, carrier, other));
  481. }
  482. }
  483. void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
  484. {
  485. for(const ExchangeCandidate & chainInfo : result)
  486. {
  487. auto carrier = chainInfo.carrierParent;
  488. auto newActor = chainInfo.actor;
  489. auto other = chainInfo.otherParent;
  490. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  491. if(!chainNodeOptional)
  492. {
  493. #if PATHFINDER_TRACE_LEVEL >= 2
  494. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  495. #endif
  496. continue;
  497. }
  498. auto exchangeNode = chainNodeOptional.get();
  499. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  500. {
  501. #if PATHFINDER_TRACE_LEVEL >= 2
  502. logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
  503. #endif
  504. continue;
  505. }
  506. if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
  507. {
  508. #if PATHFINDER_TRACE_LEVEL >= 2
  509. logAi->trace(
  510. "Exchange at %s is is not effective enough. %f < %f",
  511. exchangeNode->coord.toString(),
  512. exchangeNode->getCost(),
  513. chainInfo.getCost());
  514. #endif
  515. continue;
  516. }
  517. commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.cost);
  518. if(carrier->specialAction || carrier->chainOther)
  519. {
  520. // there is some action on source tile which should be performed before we can bypass it
  521. exchangeNode->theNodeBefore = carrier;
  522. }
  523. if(exchangeNode->actor->actorAction)
  524. {
  525. exchangeNode->theNodeBefore = carrier;
  526. exchangeNode->specialAction = exchangeNode->actor->actorAction;
  527. }
  528. exchangeNode->chainOther = other;
  529. exchangeNode->armyLoss = chainInfo.armyLoss;
  530. #if PATHFINDER_TRACE_LEVEL >= 2
  531. logAi->trace(
  532. "Chain accepted at %s %s -> %s, mask %x, cost %f, turn: %s, mp: %d, army %i",
  533. exchangeNode->coord.toString(),
  534. other->actor->toString(),
  535. exchangeNode->actor->toString(),
  536. exchangeNode->actor->chainMask,
  537. exchangeNode->getCost(),
  538. std::to_string(exchangeNode->turns),
  539. exchangeNode->moveRemains,
  540. exchangeNode->actor->armyValue);
  541. #endif
  542. heroChain.push_back(exchangeNode);
  543. }
  544. }
  545. ExchangeCandidate AINodeStorage::calculateExchange(
  546. ChainActor * exchangeActor,
  547. AIPathNode * carrierParentNode,
  548. AIPathNode * otherParentNode) const
  549. {
  550. ExchangeCandidate candidate;
  551. candidate.layer = carrierParentNode->layer;
  552. candidate.coord = carrierParentNode->coord;
  553. candidate.carrierParent = carrierParentNode;
  554. candidate.otherParent = otherParentNode;
  555. candidate.actor = exchangeActor;
  556. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  557. candidate.turns = carrierParentNode->turns;
  558. candidate.cost = carrierParentNode->cost + otherParentNode->cost / 1000.0;
  559. candidate.moveRemains = carrierParentNode->moveRemains;
  560. if(carrierParentNode->turns < otherParentNode->turns)
  561. {
  562. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  563. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  564. + carrierParentNode->moveRemains / (float)moveRemains;
  565. candidate.turns = otherParentNode->turns;
  566. candidate.cost += waitingCost;
  567. candidate.moveRemains = moveRemains;
  568. }
  569. return candidate;
  570. }
  571. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  572. {
  573. auto aiNode = getAINode(node);
  574. return aiNode->actor->hero;
  575. }
  576. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  577. {
  578. std::set<const CGHeroInstance *> heroes;
  579. for(auto actor : actors)
  580. {
  581. if(actor->hero)
  582. heroes.insert(actor->hero);
  583. }
  584. return heroes;
  585. }
  586. bool AINodeStorage::isDistanceLimitReached(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  587. {
  588. if(heroChainPass == EHeroChainPass::CHAIN && destination.node->turns > heroChainTurn)
  589. {
  590. return true;
  591. }
  592. auto aiNode = getAINode(destination.node);
  593. if(heroChainPass != EHeroChainPass::CHAIN
  594. && destination.node->turns > turnDistanceLimit[aiNode->actor->heroRole])
  595. {
  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. }