AINodeStorage.cpp 29 KB

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