AINodeStorage.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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. auto actor = std::make_shared<HeroActor>(hero.get(), mask, ai);
  412. if(hero->tempOwner != ai->playerID)
  413. {
  414. bool onLand = !actor->hero->boat;
  415. actor->initialMovement = actor->hero->maxMovePoints(onLand);
  416. }
  417. playerID = hero->tempOwner;
  418. actors.push_back(actor);
  419. }
  420. }
  421. void AINodeStorage::setTownsAndDwellings(
  422. const std::vector<const CGTownInstance *> & towns,
  423. const std::set<const CGObjectInstance *> & visitableObjs)
  424. {
  425. for(auto town : towns)
  426. {
  427. uint64_t mask = 1 << actors.size();
  428. if(!town->garrisonHero && town->getUpperArmy()->getArmyStrength())
  429. {
  430. actors.push_back(std::make_shared<TownGarrisonActor>(town, mask));
  431. }
  432. }
  433. /*auto dayOfWeek = cb->getDate(Date::DAY_OF_WEEK);
  434. auto waitForGrowth = dayOfWeek > 4;
  435. for(auto obj: visitableObjs)
  436. {
  437. const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(obj);
  438. if(dwelling)
  439. {
  440. uint64_t mask = 1 << actors.size();
  441. auto dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, false, dayOfWeek);
  442. if(dwellingActor->creatureSet->getArmyStrength())
  443. {
  444. actors.push_back(dwellingActor);
  445. }
  446. if(waitForGrowth)
  447. {
  448. mask = 1 << actors.size();
  449. dwellingActor = std::make_shared<DwellingActor>(dwelling, mask, waitForGrowth, dayOfWeek);
  450. if(dwellingActor->creatureSet->getArmyStrength())
  451. {
  452. actors.push_back(dwellingActor);
  453. }
  454. }
  455. }
  456. }*/
  457. }
  458. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  459. const PathNodeInfo & source,
  460. const PathfinderConfig * pathfinderConfig,
  461. const CPathfinderHelper * pathfinderHelper)
  462. {
  463. std::vector<CGPathNode *> neighbours;
  464. if(source.isNodeObjectVisitable())
  465. {
  466. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  467. auto srcNode = getAINode(source.node);
  468. for(auto & neighbour : accessibleExits)
  469. {
  470. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->actor);
  471. if(!node)
  472. continue;
  473. neighbours.push_back(node.get());
  474. }
  475. }
  476. if(source.isInitialPosition)
  477. {
  478. calculateTownPortalTeleportations(source, neighbours, pathfinderHelper);
  479. }
  480. return neighbours;
  481. }
  482. void AINodeStorage::calculateTownPortalTeleportations(
  483. const PathNodeInfo & source,
  484. std::vector<CGPathNode *> & neighbours,
  485. const CPathfinderHelper * pathfinderHelper)
  486. {
  487. SpellID spellID = SpellID::TOWN_PORTAL;
  488. const CSpell * townPortal = spellID.toSpell();
  489. auto srcNode = getAINode(source.node);
  490. auto hero = srcNode->actor->hero;
  491. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  492. {
  493. auto towns = cb->getTownsInfo(false);
  494. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  495. {
  496. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  497. });
  498. if(!towns.size())
  499. {
  500. return;
  501. }
  502. // TODO: Copy/Paste from TownPortalMechanics
  503. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  504. auto movementNeeded = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  505. float movementCost = (float)movementNeeded / (float)pathfinderHelper->getMaxMovePoints(EPathfindingLayer::LAND);
  506. movementCost += source.node->cost;
  507. if(source.node->moveRemains < movementNeeded)
  508. {
  509. return;
  510. }
  511. if(skillLevel < SecSkillLevel::ADVANCED)
  512. {
  513. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  514. {
  515. return source.coord.dist2dSQ(t->visitablePos());
  516. });
  517. towns = std::vector<const CGTownInstance *>{ nearestTown };
  518. }
  519. for(const CGTownInstance * targetTown : towns)
  520. {
  521. // TODO: allow to hide visiting hero in garrison
  522. if(targetTown->visitingHero)
  523. continue;
  524. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->actor->castActor);
  525. if(nodeOptional)
  526. {
  527. #ifdef VCMI_TRACE_PATHFINDER
  528. logAi->trace("Adding town portal node at %s", targetTown->name);
  529. #endif
  530. AIPathNode * node = nodeOptional.get();
  531. if(node->action == CGPathNode::UNKNOWN || node->cost > movementCost)
  532. {
  533. node->theNodeBefore = source.node;
  534. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  535. node->moveRemains = source.node->moveRemains + movementNeeded;
  536. node->cost = movementCost;
  537. }
  538. neighbours.push_back(node);
  539. }
  540. }
  541. }
  542. }
  543. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  544. {
  545. auto pos = destination.coord;
  546. auto chains = nodes[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  547. return hasBetterChain(source.node, getAINode(destination.node), chains);
  548. }
  549. template<class NodeRange>
  550. bool AINodeStorage::hasBetterChain(
  551. const CGPathNode * source,
  552. const AIPathNode * candidateNode,
  553. const NodeRange & chains) const
  554. {
  555. auto candidateActor = candidateNode->actor;
  556. for(const AIPathNode & node : chains)
  557. {
  558. auto sameNode = node.actor == candidateNode->actor;
  559. if(sameNode || node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor->hero)
  560. {
  561. continue;
  562. }
  563. if(node.danger <= candidateNode->danger && candidateNode->actor == node.actor->battleActor)
  564. {
  565. if(node.cost < candidateNode->cost)
  566. {
  567. #ifdef VCMI_TRACE_PATHFINDER
  568. logAi->trace(
  569. "Block ineficient move %s:->%s, mask=%i, mp diff: %i",
  570. source->coord.toString(),
  571. candidateNode->coord.toString(),
  572. candidateNode->actor->chainMask,
  573. node.moveRemains - candidateNode->moveRemains);
  574. #endif
  575. return true;
  576. }
  577. }
  578. if(candidateActor->actorExchangeCount == 1
  579. && (candidateActor->chainMask & node.actor->chainMask) == 0)
  580. continue;
  581. auto nodeActor = node.actor;
  582. auto nodeArmyValue = nodeActor->armyValue - node.armyLoss;
  583. auto candidateArmyValue = candidateActor->armyValue - candidateNode->armyLoss;
  584. if(nodeArmyValue > candidateArmyValue
  585. && node.cost <= candidateNode->cost)
  586. {
  587. return true;
  588. }
  589. if(nodeArmyValue == candidateArmyValue
  590. && nodeActor->heroFightingStrength >= candidateActor->heroFightingStrength
  591. && node.cost <= candidateNode->cost)
  592. {
  593. return true;
  594. }
  595. }
  596. return false;
  597. }
  598. bool AINodeStorage::isTileAccessible(const HeroPtr & hero, const int3 & pos, const EPathfindingLayer layer) const
  599. {
  600. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  601. for(const AIPathNode & node : chains)
  602. {
  603. if(node.action != CGPathNode::ENodeAction::UNKNOWN
  604. && node.actor && node.actor->hero == hero.h)
  605. {
  606. return true;
  607. }
  608. }
  609. return false;
  610. }
  611. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  612. {
  613. std::vector<AIPath> paths;
  614. paths.reserve(NUM_CHAINS / 4);
  615. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  616. for(const AIPathNode & node : chains)
  617. {
  618. if(node.action == CGPathNode::ENodeAction::UNKNOWN || !node.actor || !node.actor->hero)
  619. {
  620. continue;
  621. }
  622. AIPath path;
  623. path.targetHero = node.actor->hero;
  624. path.heroArmy = node.actor->creatureSet;
  625. path.armyLoss = node.armyLoss;
  626. path.targetObjectDanger = evaluateDanger(pos, path.targetHero);
  627. path.chainMask = node.actor->chainMask;
  628. path.exchangeCount = node.actor->actorExchangeCount;
  629. fillChainInfo(&node, path, -1);
  630. paths.push_back(path);
  631. }
  632. return paths;
  633. }
  634. void AINodeStorage::fillChainInfo(const AIPathNode * node, AIPath & path, int parentIndex) const
  635. {
  636. while(node != nullptr)
  637. {
  638. if(!node->actor->hero)
  639. return;
  640. if(node->chainOther)
  641. fillChainInfo(node->chainOther, path, parentIndex);
  642. if(node->actor->hero->visitablePos() != node->coord)
  643. {
  644. AIPathNodeInfo pathNode;
  645. pathNode.cost = node->cost;
  646. pathNode.targetHero = node->actor->hero;
  647. pathNode.specialAction = node->specialAction;
  648. pathNode.turns = node->turns;
  649. pathNode.danger = node->danger;
  650. pathNode.coord = node->coord;
  651. pathNode.parentIndex = parentIndex;
  652. parentIndex = path.nodes.size();
  653. path.nodes.push_back(pathNode);
  654. }
  655. path.specialAction = node->specialAction;
  656. node = getAINode(node->theNodeBefore);
  657. }
  658. }
  659. AIPath::AIPath()
  660. : nodes({})
  661. {
  662. }
  663. int3 AIPath::firstTileToGet() const
  664. {
  665. if(nodes.size())
  666. {
  667. return nodes.back().coord;
  668. }
  669. return int3(-1, -1, -1);
  670. }
  671. int3 AIPath::targetTile() const
  672. {
  673. if(nodes.size())
  674. {
  675. return nodes.front().coord;
  676. }
  677. return int3(-1, -1, -1);
  678. }
  679. const AIPathNodeInfo & AIPath::firstNode() const
  680. {
  681. return nodes.back();
  682. }
  683. uint64_t AIPath::getPathDanger() const
  684. {
  685. if(nodes.size())
  686. {
  687. return nodes.front().danger;
  688. }
  689. return 0;
  690. }
  691. float AIPath::movementCost() const
  692. {
  693. if(nodes.size())
  694. {
  695. return nodes.front().cost;
  696. }
  697. // TODO: boost:optional?
  698. return 0.0;
  699. }
  700. uint8_t AIPath::turn() const
  701. {
  702. if(nodes.size())
  703. {
  704. return nodes.front().turns;
  705. }
  706. // TODO: boost:optional?
  707. return 0;
  708. }
  709. uint64_t AIPath::getHeroStrength() const
  710. {
  711. return targetHero->getFightingStrength() * heroArmy->getArmyStrength();
  712. }
  713. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  714. {
  715. uint64_t pathDanger = getPathDanger();
  716. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  717. return danger;
  718. }
  719. std::string AIPath::toString()
  720. {
  721. std::stringstream str;
  722. for(auto node : nodes)
  723. str << node.targetHero->name << "->" << node.coord.toString() << "; ";
  724. return str.str();
  725. }