AINodeStorage.cpp 22 KB

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