AINodeStorage.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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.turns <= heroChainTurn && node.action != CGPathNode::ENodeAction::UNKNOWN)
  225. existingChains.push_back(&node);
  226. }
  227. for(AIPathNode * node : existingChains)
  228. {
  229. if(node->actor->isMovable)
  230. {
  231. calculateHeroChain(node, existingChains, newChains);
  232. }
  233. }
  234. cleanupInefectiveChains(newChains);
  235. addHeroChain(newChains);
  236. });
  237. return heroChain.size();
  238. }
  239. void AINodeStorage::cleanupInefectiveChains(std::vector<ExchangeCandidate> & result) const
  240. {
  241. vstd::erase_if(result, [&](ExchangeCandidate & chainInfo) -> bool
  242. {
  243. auto pos = chainInfo.coord;
  244. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  245. return hasBetterChain(chainInfo.carrierParent, &chainInfo, chains)
  246. || hasBetterChain(chainInfo.carrierParent, &chainInfo, result);
  247. });
  248. }
  249. void AINodeStorage::calculateHeroChain(
  250. AIPathNode * srcNode,
  251. const std::vector<AIPathNode *> & variants,
  252. std::vector<ExchangeCandidate> & result) const
  253. {
  254. for(AIPathNode * node : variants)
  255. {
  256. if(node == srcNode
  257. || !node->actor
  258. || 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. && carrier->action != CGPathNode::BLOCKING_VISIT
  284. && other->armyLoss < other->actor->armyValue
  285. && carrier->actor->canExchange(other->actor))
  286. {
  287. #if VCMI_TRACE_PATHFINDER >= 2
  288. logAi->trace(
  289. "Exchange allowed %s[%i] -> %s[%i] at %s",
  290. other->actor->toString(),
  291. other->actor->chainMask,
  292. carrier->actor->toString(),
  293. carrier->actor->chainMask,
  294. carrier->coord.toString());
  295. #endif
  296. if(other->actor->isMovable)
  297. {
  298. bool hasLessMp = carrier->turns > other->turns || carrier->moveRemains < other->moveRemains;
  299. bool hasLessExperience = carrier->actor->hero->exp < other->actor->hero->exp;
  300. if(hasLessMp && hasLessExperience)
  301. {
  302. #if VCMI_TRACE_PATHFINDER >= 2
  303. logAi->trace("Exchange at %s is ineficient. Blocked.", carrier->coord.toString());
  304. #endif
  305. return;
  306. }
  307. }
  308. auto newActor = carrier->actor->exchange(other->actor);
  309. result.push_back(calculateExchange(newActor, carrier, other));
  310. }
  311. }
  312. void AINodeStorage::addHeroChain(const std::vector<ExchangeCandidate> & result)
  313. {
  314. for(const ExchangeCandidate & chainInfo : result)
  315. {
  316. auto carrier = chainInfo.carrierParent;
  317. auto newActor = chainInfo.actor;
  318. auto other = chainInfo.otherParent;
  319. auto chainNodeOptional = getOrCreateNode(carrier->coord, carrier->layer, newActor);
  320. if(!chainNodeOptional)
  321. {
  322. #if VCMI_TRACE_PATHFINDER >= 2
  323. logAi->trace("Exchange at %s can not allocate node. Blocked.", carrier->coord.toString());
  324. #endif
  325. continue;
  326. }
  327. auto exchangeNode = chainNodeOptional.get();
  328. if(exchangeNode->action != CGPathNode::ENodeAction::UNKNOWN)
  329. {
  330. #if VCMI_TRACE_PATHFINDER >= 2
  331. logAi->trace("Exchange at %s node is already in use. Blocked.", carrier->coord.toString());
  332. #endif
  333. continue;
  334. }
  335. if(exchangeNode->turns != 0xFF && exchangeNode->cost < chainInfo.cost)
  336. {
  337. #if VCMI_TRACE_PATHFINDER >= 2
  338. logAi->trace(
  339. "Exchange at %s is is not effective enough. %f < %f",
  340. exchangeNode->coord.toString(),
  341. exchangeNode->cost,
  342. chainInfo.cost);
  343. #endif
  344. continue;
  345. }
  346. commit(exchangeNode, carrier, carrier->action, chainInfo.turns, chainInfo.moveRemains, chainInfo.cost);
  347. exchangeNode->chainOther = other;
  348. exchangeNode->armyLoss = chainInfo.armyLoss;
  349. #if VCMI_TRACE_PATHFINDER >= 2
  350. logAi->trace(
  351. "Chain accepted at %s %s -> %s, mask %x, cost %f, army %i",
  352. exchangeNode->coord.toString(),
  353. other->actor->toString(),
  354. exchangeNode->actor->toString(),
  355. exchangeNode->actor->chainMask,
  356. exchangeNode->cost,
  357. exchangeNode->actor->armyValue);
  358. #endif
  359. heroChain.push_back(exchangeNode);
  360. }
  361. }
  362. ExchangeCandidate AINodeStorage::calculateExchange(
  363. ChainActor * exchangeActor,
  364. AIPathNode * carrierParentNode,
  365. AIPathNode * otherParentNode) const
  366. {
  367. ExchangeCandidate candidate;
  368. candidate.layer = carrierParentNode->layer;
  369. candidate.coord = carrierParentNode->coord;
  370. candidate.carrierParent = carrierParentNode;
  371. candidate.otherParent = otherParentNode;
  372. candidate.actor = exchangeActor;
  373. candidate.armyLoss = carrierParentNode->armyLoss + otherParentNode->armyLoss;
  374. candidate.turns = carrierParentNode->turns;
  375. candidate.cost = carrierParentNode->cost + otherParentNode->cost / 1000.0;
  376. candidate.moveRemains = carrierParentNode->moveRemains;
  377. if(carrierParentNode->turns < otherParentNode->turns)
  378. {
  379. int moveRemains = exchangeActor->hero->maxMovePoints(carrierParentNode->layer);
  380. float waitingCost = otherParentNode->turns - carrierParentNode->turns - 1
  381. + carrierParentNode->moveRemains / (float)moveRemains;
  382. candidate.turns = otherParentNode->turns;
  383. candidate.cost += waitingCost;
  384. candidate.moveRemains = moveRemains;
  385. }
  386. return candidate;
  387. }
  388. const CGHeroInstance * AINodeStorage::getHero(const CGPathNode * node) const
  389. {
  390. auto aiNode = getAINode(node);
  391. return aiNode->actor->hero;
  392. }
  393. const std::set<const CGHeroInstance *> AINodeStorage::getAllHeroes() const
  394. {
  395. std::set<const CGHeroInstance *> heroes;
  396. for(auto actor : actors)
  397. {
  398. if(actor->hero)
  399. heroes.insert(actor->hero);
  400. }
  401. return heroes;
  402. }
  403. void AINodeStorage::setHeroes(std::vector<HeroPtr> heroes, const VCAI * _ai)
  404. {
  405. cb = _ai->myCb.get();
  406. ai = _ai;
  407. playerID = ai->playerID;
  408. for(auto & hero : heroes)
  409. {
  410. uint64_t mask = 1 << actors.size();
  411. playerID = hero->tempOwner;
  412. actors.push_back(std::make_shared<HeroActor>(hero.get(), mask, ai));
  413. }
  414. }
  415. void AINodeStorage::setTownsAndDwellings(
  416. const std::vector<const CGTownInstance *> & towns,
  417. const std::set<const CGObjectInstance *> & visitableObjs)
  418. {
  419. for(auto town : towns)
  420. {
  421. uint64_t mask = 1 << actors.size();
  422. if(!town->garrisonHero && town->getUpperArmy()->getArmyStrength())
  423. {
  424. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  425. }
  426. }
  427. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  428. auto waitForGrowth = dayOfWeek > 4;
  429. for(auto obj: visitableObjs)
  430. {
  431. const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  432. if(dwelling)
  433. {
  434. uint64_t mask = 1 << actors.size();
  435. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  436. if(dwellingActor->creatureSet->getArmyStrength())
  437. {
  438. actors.push_back(dwellingActor);
  439. }
  440. if(waitForGrowth)
  441. {
  442. mask = 1 << actors.size();
  443. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  444. if(dwellingActor->creatureSet->getArmyStrength())
  445. {
  446. actors.push_back(dwellingActor);
  447. }
  448. }
  449. }
  450. }*/
  451. }
  452. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  453. const PathNodeInfo & source,
  454. const PathfinderConfig * pathfinderConfig,
  455. const CPathfinderHelper * pathfinderHelper)
  456. {
  457. std::vector<CGPathNode *> neighbours;
  458. if(source.isNodeObjectVisitable())
  459. {
  460. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  461. auto srcNode = getAINode(source.node);
  462. for(auto & neighbour : accessibleExits)
  463. {
  464. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  465. if(!node)
  466. continue;
  467. neighbours.push_back(node.get());
  468. }
  469. }
  470. if(source.isInitialPosition)
  471. {
  472. calculateTownPortalTeleportations(source, neighbours, pathfinderHelper);
  473. }
  474. return neighbours;
  475. }
  476. void AINodeStorage::calculateTownPortalTeleportations(
  477. const PathNodeInfo & source,
  478. std::vector<CGPathNode *> & neighbours,
  479. const CPathfinderHelper * pathfinderHelper)
  480. {
  481. SpellID spellID = SpellID::TOWN_PORTAL;
  482. const CSpell * townPortal = spellID.toSpell();
  483. auto srcNode = getAINode(source.node);
  484. auto hero = srcNode->actor->hero;
  485. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  486. {
  487. auto towns = cb->getTownsInfo(false);
  488. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  489. {
  490. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  491. });
  492. if(!towns.size())
  493. {
  494. return;
  495. }
  496. // TODO: Copy/Paste from TownPortalMechanics
  497. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  498. auto movementNeeded = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  499. float movementCost = (float)movementNeeded / (float)pathfinderHelper->getMaxMovePoints(EPathfindingLayer::LAND);
  500. movementCost += source.node->cost;
  501. if(source.node->moveRemains < movementNeeded)
  502. {
  503. return;
  504. }
  505. if(skillLevel < SecSkillLevel::ADVANCED)
  506. {
  507. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  508. {
  509. return source.coord.dist2dSQ(t->visitablePos());
  510. });
  511. towns = std::vector<const CGTownInstance *>{ nearestTown };
  512. }
  513. for(const CGTownInstance * targetTown : towns)
  514. {
  515. // TODO: allow to hide visiting hero in garrison
  516. if(targetTown->visitingHero)
  517. continue;
  518. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->actor->castActor);
  519. if(nodeOptional)
  520. {
  521. #ifdef VCMI_TRACE_PATHFINDER
  522. logAi->trace("Adding town portal node at %s", targetTown->name);
  523. #endif
  524. AIPathNode * node = nodeOptional.get();
  525. if(node->action == CGPathNode::UNKNOWN || node->cost > movementCost)
  526. {
  527. node->theNodeBefore = source.node;
  528. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  529. node->moveRemains = source.node->moveRemains + movementNeeded;
  530. node->cost = movementCost;
  531. }
  532. neighbours.push_back(node);
  533. }
  534. }
  535. }
  536. }
  537. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  538. {
  539. auto pos = destination.coord;
  540. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  541. return hasBetterChain(source.node, getAINode(destination.node), chains);
  542. }
  543. template<class NodeRange>
  544. bool AINodeStorage::hasBetterChain(
  545. const CGPathNode * source,
  546. const AIPathNode * candidateNode,
  547. const NodeRange & chains) const
  548. {
  549. auto candidateActor = candidateNode->actor;
  550. for(const AIPathNode & node : chains)
  551. {
  552. auto sameNode = node.actor == candidateNode->actor;
  553. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  554. {
  555. continue;
  556. }
  557. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  558. {
  559. if(node.cost < candidateNode->cost)
  560. {
  561. #ifdef VCMI_TRACE_PATHFINDER
  562. logAi->trace(
  563. "Block ineficient move %s:->%s, mask=%i, mp diff: %i",
  564. source->coord.toString(),
  565. candidateNode->coord.toString(),
  566. candidateNode->actor->chainMask,
  567. node.moveRemains - candidateNode->moveRemains);
  568. #endif
  569. return true;
  570. }
  571. }
  572. if(candidateActor->actorExchangeCount == 1
  573. && (candidateActor->chainMask & node.actor->chainMask) == 0)
  574. continue;
  575. auto nodeActor = node.actor;
  576. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  577. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  578. if(nodeArmyValue > candidateArmyValue
  579. && node.cost <= candidateNode->cost)
  580. {
  581. return true;
  582. }
  583. if(nodeArmyValue == candidateArmyValue
  584. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  585. && node.cost <= candidateNode->cost)
  586. {
  587. return true;
  588. }
  589. }
  590. return false;
  591. }
  592. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  593. {
  594. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  595. for(const AIPathNode & node : chains)
  596. {
  597. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  598. && node.actor && node.actor->hero == hero.h)
  599. {
  600. return true;
  601. }
  602. }
  603. return false;
  604. }
  605. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  606. {
  607. std::vector<AIPath> paths;
  608. paths.reserve(NUM_CHAINS / 4);
  609. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  610. for(const AIPathNode & node : chains)
  611. {
  612. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  613. {
  614. continue;
  615. }
  616. AIPath path;
  617. path.targetHero = node.actor->hero;
  618. path.heroArmy = node.actor->creatureSet;
  619. path.armyLoss = node.armyLoss;
  620. path.targetObjectDanger = evaluateDanger(pos, path.targetHero);
  621. path.chainMask = node.actor->chainMask;
  622. path.exchangeCount = node.actor->actorExchangeCount;
  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. }