AINodeStorage.cpp 11 KB

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