AINodeStorage.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 "../../../lib/callback/IGameInfoCallback.h"
  14. #include "../../../lib/mapping/CMap.h"
  15. #include "../../../lib/pathfinder/CPathfinder.h"
  16. #include "../../../lib/pathfinder/PathfinderOptions.h"
  17. #include "../../../lib/pathfinder/PathfinderUtil.h"
  18. #include "../../../lib/spells/ISpellMechanics.h"
  19. #include "../../../lib/spells/adventure/TownPortalEffect.h"
  20. #include "../../../lib/IGameSettings.h"
  21. #include "../../../lib/CPlayerState.h"
  22. AINodeStorage::AINodeStorage(const int3 & Sizes)
  23. : sizes(Sizes)
  24. {
  25. nodes.resize(boost::extents[EPathfindingLayer::NUM_LAYERS][sizes.z][sizes.x][sizes.y][NUM_CHAINS]);
  26. dangerEvaluator.reset(new FuzzyHelper());
  27. }
  28. AINodeStorage::~AINodeStorage() = default;
  29. void AINodeStorage::initialize(const PathfinderOptions & options, const IGameInfoCallback & gameInfo)
  30. {
  31. int3 pos;
  32. const int3 sizes = gameInfo.getMapSize();
  33. const auto & fow = gameInfo.getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  34. const PlayerColor player = hero->tempOwner;
  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.z=0; pos.z < sizes.z; ++pos.z)
  39. {
  40. for(pos.x=0; pos.x < sizes.x; ++pos.x)
  41. {
  42. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  43. {
  44. const TerrainTile * tile = gameInfo.getTile(pos);
  45. if(!tile->getTerrain()->isPassable())
  46. continue;
  47. if(tile->getTerrain()->isWater())
  48. {
  49. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, *tile, fow, player, gameInfo));
  50. if(useFlying)
  51. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, *tile, fow, player, gameInfo));
  52. if(useWaterWalking)
  53. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, *tile, fow, player, gameInfo));
  54. }
  55. else
  56. {
  57. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, *tile, fow, player, gameInfo));
  58. if(useFlying)
  59. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, *tile, fow, player, gameInfo));
  60. }
  61. }
  62. }
  63. }
  64. }
  65. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  66. {
  67. return static_cast<const AIPathNode *>(node);
  68. }
  69. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  70. {
  71. auto aiNode = static_cast<AIPathNode *>(node);
  72. updater(aiNode);
  73. }
  74. bool AINodeStorage::isBattleNode(const CGPathNode * node) const
  75. {
  76. return (getAINode(node)->chainMask & BATTLE_CHAIN) > 0;
  77. }
  78. std::optional<AIPathNode *> AINodeStorage::getOrCreateNode(const int3 & pos, const EPathfindingLayer layer, int chainNumber)
  79. {
  80. auto chains = nodes[layer.getNum()][pos.z][pos.x][pos.y];
  81. for(AIPathNode & node : chains)
  82. {
  83. if(node.chainMask == chainNumber)
  84. {
  85. return &node;
  86. }
  87. if(node.chainMask == 0)
  88. {
  89. node.chainMask = chainNumber;
  90. return &node;
  91. }
  92. }
  93. return std::nullopt;
  94. }
  95. std::vector<CGPathNode *> AINodeStorage::getInitialNodes()
  96. {
  97. auto hpos = hero->visitablePos();
  98. auto initialNode = getOrCreateNode(hpos, hero->inBoat() ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND, NORMAL_CHAIN).value();
  99. initialNode->turns = 0;
  100. initialNode->moveRemains = hero->movementPointsRemaining();
  101. initialNode->danger = 0;
  102. initialNode->setCost(0.0);
  103. return {initialNode};
  104. }
  105. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, EPathAccessibility accessibility)
  106. {
  107. for(int i = 0; i < NUM_CHAINS; i++)
  108. {
  109. AIPathNode & heroNode = nodes[layer.getNum()][coord.z][coord.x][coord.y][i];
  110. heroNode.chainMask = 0;
  111. heroNode.danger = 0;
  112. heroNode.manaCost = 0;
  113. heroNode.specialAction.reset();
  114. heroNode.update(coord, layer, accessibility);
  115. }
  116. }
  117. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  118. {
  119. const AIPathNode * srcNode = getAINode(source.node);
  120. updateAINode(destination.node, [&](AIPathNode * dstNode)
  121. {
  122. dstNode->moveRemains = destination.movementLeft;
  123. dstNode->turns = destination.turn;
  124. dstNode->setCost(destination.cost);
  125. dstNode->danger = srcNode->danger;
  126. dstNode->action = destination.action;
  127. dstNode->theNodeBefore = srcNode->theNodeBefore;
  128. dstNode->manaCost = srcNode->manaCost;
  129. if(dstNode->specialAction)
  130. {
  131. dstNode->specialAction->applyOnDestination(getHero(), destination, source, dstNode, srcNode);
  132. }
  133. });
  134. }
  135. void AINodeStorage::calculateNeighbours(
  136. std::vector<CGPathNode *> & result,
  137. const PathNodeInfo & source,
  138. EPathfindingLayer layer,
  139. const PathfinderConfig * pathfinderConfig,
  140. const CPathfinderHelper * pathfinderHelper)
  141. {
  142. NeighbourTilesVector accessibleNeighbourTiles;
  143. result.clear();
  144. pathfinderHelper->calculateNeighbourTiles(accessibleNeighbourTiles, source);
  145. const AIPathNode * srcNode = getAINode(source.node);
  146. for(auto & neighbour : accessibleNeighbourTiles)
  147. {
  148. for(EPathfindingLayer i = EPathfindingLayer::LAND; i < EPathfindingLayer::NUM_LAYERS; i.advance(1))
  149. {
  150. auto nextNode = getOrCreateNode(neighbour, i, srcNode->chainMask);
  151. if(!nextNode || nextNode.value()->accessible == EPathAccessibility::NOT_SET)
  152. continue;
  153. result.push_back(nextNode.value());
  154. }
  155. }
  156. }
  157. void AINodeStorage::setHero(HeroPtr heroPtr, const VCAI * _ai)
  158. {
  159. hero = heroPtr.get();
  160. cb = _ai->myCb.get();
  161. ai = _ai;
  162. }
  163. std::vector<CGPathNode *> AINodeStorage::calculateTeleportations(
  164. const PathNodeInfo & source,
  165. const PathfinderConfig * pathfinderConfig,
  166. const CPathfinderHelper * pathfinderHelper)
  167. {
  168. std::vector<CGPathNode *> neighbours;
  169. if(source.isNodeObjectVisitable())
  170. {
  171. auto accessibleExits = pathfinderHelper->getTeleportExits(source);
  172. auto srcNode = getAINode(source.node);
  173. for(auto & neighbour : accessibleExits)
  174. {
  175. auto node = getOrCreateNode(neighbour, source.node->layer, srcNode->chainMask);
  176. if(!node)
  177. continue;
  178. neighbours.push_back(node.value());
  179. }
  180. }
  181. if(hero->visitablePos() == source.coord)
  182. {
  183. calculateTownPortalTeleportations(source, neighbours);
  184. }
  185. return neighbours;
  186. }
  187. void AINodeStorage::calculateTownPortalTeleportations(
  188. const PathNodeInfo & source,
  189. std::vector<CGPathNode *> & neighbours)
  190. {
  191. auto srcNode = getAINode(source.node);
  192. for (const auto & spell : LIBRARY->spellh->objects)
  193. {
  194. if (!spell || !spell->isAdventure())
  195. continue;
  196. auto townPortalEffect = spell->getAdventureMechanics().getEffectAs<TownPortalEffect>(hero);
  197. if (!townPortalEffect)
  198. continue;
  199. if(!hero->canCastThisSpell(spell.get()) || hero->mana < hero->getSpellCost(spell.get()))
  200. continue;
  201. auto towns = cb->getTownsInfo(false);
  202. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  203. {
  204. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  205. });
  206. if(towns.empty())
  207. return;
  208. if(hero->movementPointsRemaining() < townPortalEffect->getMovementPointsRequired())
  209. {
  210. return;
  211. }
  212. if(!townPortalEffect->townSelectionAllowed())
  213. {
  214. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  215. {
  216. return hero->visitablePos().dist2dSQ(t->visitablePos());
  217. });
  218. towns = std::vector<const CGTownInstance *>{ nearestTown };
  219. }
  220. for(const CGTownInstance * targetTown : towns)
  221. {
  222. if(targetTown->getVisitingHero())
  223. continue;
  224. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->chainMask | CAST_CHAIN);
  225. if(nodeOptional)
  226. {
  227. #ifdef VCMI_TRACE_PATHFINDER
  228. logAi->trace("Adding town portal node at %s", targetTown->name);
  229. #endif
  230. AIPathNode * node = nodeOptional.value();
  231. node->theNodeBefore = source.node;
  232. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown, spell->id));
  233. node->moveRemains = source.node->moveRemains;
  234. neighbours.push_back(node);
  235. }
  236. }
  237. }
  238. }
  239. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  240. {
  241. auto pos = destination.coord;
  242. auto chains = nodes[EPathfindingLayer::LAND][pos.z][pos.x][pos.y];
  243. auto destinationNode = getAINode(destination.node);
  244. for(const AIPathNode & node : chains)
  245. {
  246. auto sameNode = node.chainMask == destinationNode->chainMask;
  247. if(sameNode || node.action == EPathNodeAction::UNKNOWN)
  248. {
  249. continue;
  250. }
  251. if(node.danger <= destinationNode->danger && destinationNode->chainMask == 1 && node.chainMask == 0)
  252. {
  253. if(node.getCost() < destinationNode->getCost())
  254. {
  255. #ifdef VCMI_TRACE_PATHFINDER
  256. logAi->trace(
  257. "Block inefficient move %s:->%s, mask=%i, mp diff: %i",
  258. source.coord.toString(),
  259. destination.coord.toString(),
  260. destinationNode->chainMask,
  261. node.moveRemains - destinationNode->moveRemains);
  262. #endif
  263. return true;
  264. }
  265. }
  266. }
  267. return false;
  268. }
  269. bool AINodeStorage::isTileAccessible(const int3 & pos, const EPathfindingLayer layer) const
  270. {
  271. return nodes[layer.getNum()][pos.z][pos.x][pos.y][0].action != EPathNodeAction::UNKNOWN;
  272. }
  273. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  274. {
  275. std::vector<AIPath> paths;
  276. auto chains = nodes[isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL][pos.z][pos.x][pos.y];
  277. auto initialPos = hero->visitablePos();
  278. for(const AIPathNode & node : chains)
  279. {
  280. if(node.action == EPathNodeAction::UNKNOWN)
  281. {
  282. continue;
  283. }
  284. AIPath path;
  285. const AIPathNode * current = &node;
  286. while(current != nullptr && current->coord != initialPos)
  287. {
  288. AIPathNodeInfo pathNode;
  289. pathNode.cost = current->getCost();
  290. pathNode.turns = current->turns;
  291. pathNode.danger = current->danger;
  292. pathNode.coord = current->coord;
  293. path.nodes.push_back(pathNode);
  294. path.specialAction = current->specialAction;
  295. current = getAINode(current->theNodeBefore);
  296. }
  297. path.targetObjectDanger = evaluateDanger(pos);
  298. paths.push_back(path);
  299. }
  300. return paths;
  301. }
  302. AIPath::AIPath()
  303. : nodes({})
  304. {
  305. }
  306. int3 AIPath::firstTileToGet() const
  307. {
  308. if(nodes.size())
  309. {
  310. return nodes.back().coord;
  311. }
  312. return int3(-1, -1, -1);
  313. }
  314. uint64_t AIPath::getPathDanger() const
  315. {
  316. if(nodes.size())
  317. {
  318. return nodes.front().danger;
  319. }
  320. return 0;
  321. }
  322. float AIPath::movementCost() const
  323. {
  324. if(nodes.size())
  325. {
  326. return nodes.front().cost;
  327. }
  328. // TODO: boost:optional?
  329. return 0.0;
  330. }
  331. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  332. {
  333. uint64_t pathDanger = getPathDanger();
  334. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  335. return danger;
  336. }