AINodeStorage.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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 "../../../CCallback.h"
  15. #include "../../../lib/mapping/CMap.h"
  16. #include "../../../lib/mapObjects/MapObjects.h"
  17. #include "../../../lib/PathfinderUtil.h"
  18. #include "../../../lib/CPlayerState.h"
  19. AINodeStorage::AINodeStorage(const int3 & Sizes)
  20. : sizes(Sizes)
  21. {
  22. nodes.resize(boost::extents[sizes.x][sizes.y][sizes.z][EPathfindingLayer::NUM_LAYERS][NUM_CHAINS]);
  23. dangerEvaluator.reset(new FuzzyHelper());
  24. }
  25. AINodeStorage::~AINodeStorage() = default;
  26. void AINodeStorage::initialize(const PathfinderOptions & options, const CGameState * gs)
  27. {
  28. if(heroChainPass)
  29. return;
  30. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  31. int3 pos;
  32. const PlayerColor player = ai->playerID;
  33. const int3 sizes = gs->getMapSize();
  34. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->getPlayerTeam(player)->fogOfWarMap;
  35. //make 200% sure that these are loop invariants (also a bit shorter code), let compiler do the rest(loop unswitching)
  36. const bool useFlying = options.useFlying;
  37. const bool useWaterWalking = options.useWaterWalking;
  38. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  39. {
  40. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  41. {
  42. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  43. {
  44. const TerrainTile * tile = &gs->map->getTile(pos);
  45. switch(tile->terType)
  46. {
  47. case ETerrainType::ROCK:
  48. break;
  49. case ETerrainType::WATER:
  50. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  51. if(useFlying)
  52. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  53. if(useWaterWalking)
  54. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  55. break;
  56. default:
  57. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  58. if(useFlying)
  59. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  60. break;
  61. }
  62. }
  63. }
  64. }
  65. }
  66. void AINodeStorage::clear()
  67. {
  68. actors.clear();
  69. heroChainPass = false;
  70. heroChainTurn = 0;
  71. }
  72. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  73. {
  74. return static_cast<const AIPathNode *>(node);
  75. }
  76. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  77. {
  78. auto aiNode = static_cast<AIPathNode *>(node);
  79. updater(aiNode);
  80. }
  81. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(
  82. const int3 & pos,
  83. const EPathfindingLayer layer,
  84. const ChainActor * actor)
  85. {
  86. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  87. for(AIPathNode & node : chains)
  88. {
  89. if(node.actor == actor)
  90. {
  91. return &node;
  92. }
  93. if(!node.actor)
  94. {
  95. node.actor = actor;
  96. return &node;
  97. }
  98. }
  99. return boost::none;
  100. }
  101. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  102. {
  103. if(heroChainPass)
  104. return heroChain;
  105. std::vector<CGPathNode *> initialNodes;
  106. for(auto actorPtr : actors)
  107. {
  108. ChainActor * actor = actorPtr.get();
  109. AIPathNode * initialNode =
  110. getOrCreateNode(actor->initialPosition, actor->layer, actor)
  111. .get();
  112. initialNode->turns = actor->initialTurn;
  113. initialNode->moveRemains = actor->initialMovement;
  114. initialNode->danger = 0;
  115. initialNode->cost = actor->initialTurn;
  116. initialNode->action = CGPathNode::ENodeAction::NORMAL;
  117. if(actor->isMovable)
  118. {
  119. initialNodes.push_back(initialNode);
  120. }
  121. else
  122. {
  123. initialNode->locked = true;
  124. }
  125. }
  126. return initialNodes;
  127. }
  128. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  129. {
  130. for(int i = 0; i < NUM_CHAINS; i++)
  131. {
  132. AIPathNode & heroNode = nodes[coord.x][coord.y][coord.z][layer][i];
  133. heroNode.actor = nullptr;
  134. heroNode.danger = 0;
  135. heroNode.manaCost = 0;
  136. heroNode.specialAction.reset();
  137. heroNode.armyLoss = 0;
  138. heroNode.chainOther = nullptr;
  139. heroNode.update(coord, layer, accessibility);
  140. }
  141. }
  142. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  143. {
  144. const AIPathNode * srcNode = getAINode(source.node);
  145. updateAINode(destination.node, [&](AIPathNode * dstNode)
  146. {
  147. commit(dstNode, srcNode, destination.action, destination.turn, destination.movementLeft, destination.cost);
  148. if(srcNode->specialAction || srcNode->chainOther)
  149. {
  150. // there is some action on source tile which should be performed before we can bypass it
  151. destination.node->theNodeBefore = source.node;
  152. }
  153. if(dstNode->specialAction && dstNode->actor)
  154. {
  155. dstNode->specialAction->applyOnDestination(dstNode->actor->hero, destination, source, dstNode, srcNode);
  156. }
  157. #ifdef VCMI_TRACE_PATHFINDER_EX
  158. logAi->trace(
  159. "Commited %s -> %s, cost: %f, hero: %s, mask: %x, army: %i",
  160. source.coord.toString(),
  161. destination.coord.toString(),
  162. destination.cost,
  163. dstNode->actor->toString(),
  164. dstNode->actor->chainMask,
  165. dstNode->actor->armyValue);
  166. #endif
  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. }
  187. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  188. const PathNodeInfo & source,
  189. const PathfinderConfig * pathfinderConfig,
  190. const CPathfinderHelper * pathfinderHelper)
  191. {
  192. std::vector<CGPathNode *> neighbours;
  193. neighbours.reserve(16);
  194. const AIPathNode * srcNode = getAINode(source.node);
  195. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  196. for(auto & neighbour : accessibleNeighbourTiles)
  197. {
  198. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  199. {
  200. auto nextNode = getOrCreateNode(neighbour, i, srcNode->actor);
  201. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  202. continue;
  203. neighbours.push_back(nextNode.get());
  204. }
  205. }
  206. return neighbours;
  207. }
  208. bool AINodeStorage::calculateHeroChain()
  209. {
  210. heroChainPass = true;
  211. heroChain.resize(0);
  212. std::vector<AIPathNode *> existingChains;
  213. std::vector<ExchangeCandidate> newChains;
  214. existingChains.reserve(NUM_CHAINS);
  215. newChains.reserve(NUM_CHAINS);
  216. foreach_tile_pos([&](const int3 & pos) {
  217. auto layer = EPathfindingLayer::LAND;
  218. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  219. existingChains.resize(0);
  220. newChains.resize(0);
  221. for(AIPathNode & node : chains)
  222. {
  223. if(node.coord.x == 60 && node.coord.y == 56 && node.actor)
  224. logAi->trace(node.actor->toString());
  225. if(node.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  226. existingChains.push_back(&node);
  227. }
  228. for(AIPathNode * node : existingChains)
  229. {
  230. if(node->actor->isMovable)
  231. {
  232. calculateHeroChain(node, existingChains, newChains);
  233. }
  234. }
  235. cleanupInefectiveChains(newChains);
  236. addHeroChain(newChains);
  237. });
  238. return heroChain.size();
  239. }
  240. void AINodeStorage::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  241. {
  242. vstd::erase_if(result, [&](ExchangeCandidate & chainInfo) -> bool
  243. {
  244. auto pos = chainInfo.coord;
  245. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  246. return hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  247. || hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  248. });
  249. }
  250. void AINodeStorage::calculateHeroChain(
  251. AIPathNode * srcNode,
  252. const std::vector<AIPathNode *> & variants,
  253. std::vector<ExchangeCandidate> & result) const
  254. {
  255. for(AIPathNode * node : variants)
  256. {
  257. if(node == srcNode || !node->actor || node->turns > heroChainTurn
  258. || node->action == CGPathNode::ENodeAction::UNKNOWN && node->actor->hero
  259. || (node->actor->chainMask & srcNode->actor->chainMask) != 0)
  260. {
  261. continue;
  262. }
  263. #ifdef VCMI_TRACE_PATHFINDER_EX
  264. logAi->trace(
  265. "Thy exchange %s[%i] -> %s[%i] at %s",
  266. node->actor->toString(),
  267. node->actor->chainMask,
  268. srcNode->actor->toString(),
  269. srcNode->actor->chainMask,
  270. srcNode->coord.toString());
  271. #endif
  272. calculateHeroChain(srcNode, node, result);
  273. }
  274. }
  275. void AINodeStorage::calculateHeroChain(
  276. AIPathNode * carrier,
  277. AIPathNode * other,
  278. std::vector<ExchangeCandidate> & result) const
  279. {
  280. if(carrier->actor->canExchange(other->actor))
  281. {
  282. #ifdef VCMI_TRACE_PATHFINDER_EX
  283. logAi->trace(
  284. "Exchange allowed %s[%i] -> %s[%i] at %s",
  285. other->actor->toString(),
  286. other->actor->chainMask,
  287. carrier->actor->toString(),
  288. carrier->actor->chainMask,
  289. carrier->coord.toString());
  290. #endif
  291. bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains;
  292. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  293. if(hasLessMp && hasLessExperience)
  294. {
  295. #ifdef VCMI_TRACE_PATHFINDER_EX
  296. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  297. #endif
  298. return;
  299. }
  300. auto newActor = carrier->actor->exchange(other->actor);
  301. result.push_back(calculateExchange(newActor, carrier, other));
  302. }
  303. }
  304. void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
  305. {
  306. for(const ExchangeCandidate & chainInfo : result)
  307. {
  308. auto carrier = chainInfo.carrierParent;
  309. auto newActor = chainInfo.actor;
  310. auto other = chainInfo.otherParent;
  311. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  312. if(!chainNodeOptional)
  313. {
  314. #ifdef VCMI_TRACE_PATHFINDER_EX
  315. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  316. #endif
  317. continue;
  318. }
  319. auto exchangeNode = chainNodeOptional.get();
  320. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  321. {
  322. #ifdef VCMI_TRACE_PATHFINDER_EX
  323. logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
  324. #endif
  325. continue;
  326. }
  327. if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
  328. {
  329. #ifdef VCMI_TRACE_PATHFINDER_EX
  330. logAi->trace(
  331. "Exchange at %s is is not effective enough. %f < %f",
  332. exchangeNode->coord.toString(),
  333. exchangeNode->cost,
  334. chainInfo.cost);
  335. #endif
  336. continue;
  337. }
  338. commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.cost);
  339. exchangeNode->chainOther = other;
  340. exchangeNode->armyLoss = chainInfo.armyLoss;
  341. #ifdef VCMI_TRACE_PATHFINDER_EX
  342. logAi->trace(
  343. "Chain accepted at %s %s -> %s, mask %x, cost %f, army %i",
  344. exchangeNode->coord.toString(),
  345. other->actor->toString(),
  346. exchangeNode->actor->toString(),
  347. exchangeNode->actor->chainMask,
  348. exchangeNode->cost,
  349. exchangeNode->actor->armyValue);
  350. #endif
  351. heroChain.push_back(exchangeNode);
  352. }
  353. }
  354. ExchangeCandidate AINodeStorage::calculateExchange(
  355. ChainActor * exchangeActor,
  356. AIPathNode * carrierParentNode,
  357. AIPathNode * otherParentNode) const
  358. {
  359. ExchangeCandidate candidate;
  360. auto carrierActor = carrierParentNode->actor;
  361. auto otherActor = otherParentNode->actor;
  362. candidate.layer = carrierParentNode->layer;
  363. candidate.coord = carrierParentNode->coord;
  364. candidate.carrierParent = carrierParentNode;
  365. candidate.otherParent = otherParentNode;
  366. candidate.actor = exchangeActor;
  367. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  368. candidate.turns = carrierParentNode->turns;
  369. candidate.cost = carrierParentNode->cost + otherParentNode->cost / 1000.0;
  370. candidate.moveRemains = carrierParentNode->moveRemains;
  371. if(carrierParentNode->turns < otherParentNode->turns)
  372. {
  373. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  374. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  375. + carrierParentNode->moveRemains / (float)moveRemains;
  376. candidate.turns = otherParentNode->turns;
  377. candidate.cost += waitingCost;
  378. candidate.moveRemains = moveRemains;
  379. }
  380. return candidate;
  381. }
  382. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  383. {
  384. auto aiNode = getAINode(node);
  385. return aiNode->actor->hero;
  386. }
  387. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  388. {
  389. std::set<const CGHeroInstance *> heroes;
  390. for(auto actor : actors)
  391. {
  392. if(actor->hero)
  393. heroes.insert(actor->hero);
  394. }
  395. return heroes;
  396. }
  397. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  398. {
  399. cb = _ai->myCb.get();
  400. ai = _ai;
  401. for(auto & hero : heroes)
  402. {
  403. uint64_t mask = 1 << actors.size();
  404. actors.push_back(std::make_shared<HeroActor>(hero.get(), mask, ai));
  405. }
  406. }
  407. void AINodeStorage::setTownsAndDwellings(
  408. const std::vector<const CGTownInstance *> & towns,
  409. const std::set<const CGObjectInstance *> & visitableObjs)
  410. {
  411. for(auto town : towns)
  412. {
  413. uint64_t mask = 1 << actors.size();
  414. if(town->getUpperArmy()->getArmyStrength())
  415. {
  416. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  417. }
  418. }
  419. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  420. auto waitForGrowth = dayOfWeek > 4;
  421. for(auto obj: visitableObjs)
  422. {
  423. const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  424. if(dwelling)
  425. {
  426. uint64_t mask = 1 << actors.size();
  427. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  428. if(dwellingActor->creatureSet->getArmyStrength())
  429. {
  430. actors.push_back(dwellingActor);
  431. }
  432. if(waitForGrowth)
  433. {
  434. mask = 1 << actors.size();
  435. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  436. if(dwellingActor->creatureSet->getArmyStrength())
  437. {
  438. actors.push_back(dwellingActor);
  439. }
  440. }
  441. }
  442. }*/
  443. }
  444. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  445. const PathNodeInfo & source,
  446. const PathfinderConfig * pathfinderConfig,
  447. const CPathfinderHelper * pathfinderHelper)
  448. {
  449. std::vector<CGPathNode *> neighbours;
  450. if(source.isNodeObjectVisitable())
  451. {
  452. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  453. auto srcNode = getAINode(source.node);
  454. for(auto & neighbour : accessibleExits)
  455. {
  456. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  457. if(!node)
  458. continue;
  459. neighbours.push_back(node.get());
  460. }
  461. }
  462. if(source.isInitialPosition)
  463. {
  464. calculateTownPortalTeleportations(source, neighbours);
  465. }
  466. return neighbours;
  467. }
  468. void AINodeStorage::calculateTownPortalTeleportations(
  469. const PathNodeInfo & source,
  470. std::vector<CGPathNode *> & neighbours)
  471. {
  472. SpellID spellID = SpellID::TOWN_PORTAL;
  473. const CSpell * townPortal = spellID.toSpell();
  474. auto srcNode = getAINode(source.node);
  475. auto hero = srcNode->actor->hero;
  476. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  477. {
  478. auto towns = cb->getTownsInfo(false);
  479. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  480. {
  481. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  482. });
  483. if(!towns.size())
  484. {
  485. return;
  486. }
  487. // TODO: Copy/Paste from TownPortalMechanics
  488. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  489. auto movementCost = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  490. if(hero->movement < movementCost)
  491. {
  492. return;
  493. }
  494. if(skillLevel < SecSkillLevel::ADVANCED)
  495. {
  496. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  497. {
  498. return hero->visitablePos().dist2dSQ(t->visitablePos());
  499. });
  500. towns = std::vector<const CGTownInstance *>{ nearestTown };
  501. }
  502. for(const CGTownInstance * targetTown : towns)
  503. {
  504. if(targetTown->visitingHero)
  505. continue;
  506. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->actor->castActor);
  507. if(nodeOptional)
  508. {
  509. #ifdef VCMI_TRACE_PATHFINDER
  510. logAi->trace("Adding town portal node at %s", targetTown->name);
  511. #endif
  512. AIPathNode * node = nodeOptional.get();
  513. node->theNodeBefore = source.node;
  514. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  515. node->moveRemains = source.node->moveRemains;
  516. neighbours.push_back(node);
  517. }
  518. }
  519. }
  520. }
  521. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  522. {
  523. auto pos = destination.coord;
  524. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  525. return hasBetterChain(source.node, getAINode(destination.node), chains);
  526. }
  527. template<class NodeRange>
  528. bool AINodeStorage::hasBetterChain(
  529. const CGPathNode * source,
  530. const AIPathNode * candidateNode,
  531. const NodeRange & chains) const
  532. {
  533. auto candidateActor = candidateNode->actor;
  534. for(const AIPathNode & node : chains)
  535. {
  536. auto sameNode = node.actor == candidateNode->actor;
  537. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  538. {
  539. continue;
  540. }
  541. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  542. {
  543. if(node.cost < candidateNode->cost)
  544. {
  545. #ifdef VCMI_TRACE_PATHFINDER
  546. logAi->trace(
  547. "Block ineficient move %s:->%s, mask=%i, mp diff: %i",
  548. source->coord.toString(),
  549. candidateNode->coord.toString(),
  550. candidateNode->actor->chainMask,
  551. node.moveRemains - candidateNode->moveRemains);
  552. #endif
  553. return true;
  554. }
  555. }
  556. if(candidateActor->actorExchangeCount == 1
  557. && (candidateActor->chainMask & node.actor->chainMask) == 0)
  558. continue;
  559. auto nodeActor = node.actor;
  560. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  561. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  562. if(nodeArmyValue > candidateArmyValue
  563. && node.cost <= candidateNode->cost)
  564. {
  565. return true;
  566. }
  567. if(nodeArmyValue == candidateArmyValue
  568. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  569. && node.cost <= candidateNode->cost)
  570. {
  571. return true;
  572. }
  573. }
  574. return false;
  575. }
  576. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  577. {
  578. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  579. for(const AIPathNode & node : chains)
  580. {
  581. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  582. && node.actor && node.actor->hero == hero.h)
  583. {
  584. return true;
  585. }
  586. }
  587. return false;
  588. }
  589. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  590. {
  591. std::vector<AIPath> paths;
  592. paths.reserve(NUM_CHAINS / 4);
  593. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  594. for(const AIPathNode & node : chains)
  595. {
  596. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  597. {
  598. continue;
  599. }
  600. AIPath path;
  601. path.targetHero = node.actor->hero;
  602. path.heroArmy = node.actor->creatureSet;
  603. path.armyLoss = node.armyLoss;
  604. path.targetObjectDanger = evaluateDanger(pos, path.targetHero);
  605. path.chainMask = node.actor->chainMask;
  606. fillChainInfo(&node, path, -1);
  607. paths.push_back(path);
  608. }
  609. return paths;
  610. }
  611. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  612. {
  613. while(node != nullptr)
  614. {
  615. if(!node->actor->hero)
  616. return;
  617. if(node->chainOther)
  618. fillChainInfo(node->chainOther, path, parentIndex);
  619. if(node->actor->hero->visitablePos() != node->coord)
  620. {
  621. AIPathNodeInfo pathNode;
  622. pathNode.cost = node->cost;
  623. pathNode.targetHero = node->actor->hero;
  624. pathNode.turns = node->turns;
  625. pathNode.danger = node->danger;
  626. pathNode.coord = node->coord;
  627. pathNode.parentIndex = parentIndex;
  628. parentIndex = path.nodes.size();
  629. path.nodes.push_back(pathNode);
  630. }
  631. path.specialAction = node->specialAction;
  632. node = getAINode(node->theNodeBefore);
  633. }
  634. }
  635. AIPath::AIPath()
  636. : nodes({})
  637. {
  638. }
  639. int3 AIPath::firstTileToGet() const
  640. {
  641. if(nodes.size())
  642. {
  643. return nodes.back().coord;
  644. }
  645. return int3(-1, -1, -1);
  646. }
  647. const AIPathNodeInfo & AIPath::firstNode() const
  648. {
  649. return nodes.back();
  650. }
  651. uint64_t AIPath::getPathDanger() const
  652. {
  653. if(nodes.size())
  654. {
  655. return nodes.front().danger;
  656. }
  657. return 0;
  658. }
  659. float AIPath::movementCost() const
  660. {
  661. if(nodes.size())
  662. {
  663. return nodes.front().cost;
  664. }
  665. // TODO: boost:optional?
  666. return 0.0;
  667. }
  668. uint64_t AIPath::getHeroStrength() const
  669. {
  670. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  671. }
  672. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  673. {
  674. uint64_t pathDanger = getPathDanger();
  675. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  676. return danger;
  677. }