AINodeStorage.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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 "../../../lib/callback/IGameCallback.h"
  15. #include "../../../lib/mapping/CMap.h"
  16. #include "../../../lib/mapObjects/MapObjects.h"
  17. #include "../../../lib/pathfinder/CPathfinder.h"
  18. #include "../../../lib/pathfinder/PathfinderOptions.h"
  19. #include "../../../lib/pathfinder/PathfinderUtil.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 CGameState * gs)
  30. {
  31. int3 pos;
  32. const int3 sizes = gs->getMapSize();
  33. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->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 = gs->getMap().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, gs));
  50. if(useFlying)
  51. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  52. if(useWaterWalking)
  53. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  54. }
  55. else
  56. {
  57. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  58. if(useFlying)
  59. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  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. SpellID spellID = SpellID::TOWN_PORTAL;
  192. const CSpell * townPortal = spellID.toSpell();
  193. auto srcNode = getAINode(source.node);
  194. if(hero->canCastThisSpell(townPortal) && hero->mana >= hero->getSpellCost(townPortal))
  195. {
  196. auto towns = cb->getTownsInfo(false);
  197. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  198. {
  199. return cb->getPlayerRelations(hero->tempOwner, t->tempOwner) == PlayerRelations::ENEMIES;
  200. });
  201. if(!towns.size())
  202. {
  203. return;
  204. }
  205. // TODO: Copy/Paste from TownPortalMechanics
  206. auto skillLevel = hero->getSpellSchoolLevel(townPortal);
  207. int baseCost = hero->cb->getSettings().getInteger(EGameSettings::HEROES_MOVEMENT_COST_BASE);
  208. auto movementCost = baseCost * (skillLevel >= 3 ? 2 : 3);
  209. if(hero->movementPointsRemaining() < movementCost)
  210. {
  211. return;
  212. }
  213. if(skillLevel < MasteryLevel::ADVANCED)
  214. {
  215. const CGTownInstance * nearestTown = *vstd::minElementByFun(towns, [&](const CGTownInstance * t) -> int
  216. {
  217. return hero->visitablePos().dist2dSQ(t->visitablePos());
  218. });
  219. towns = std::vector<const CGTownInstance *>{ nearestTown };
  220. }
  221. for(const CGTownInstance * targetTown : towns)
  222. {
  223. if(targetTown->getVisitingHero())
  224. continue;
  225. auto nodeOptional = getOrCreateNode(targetTown->visitablePos(), EPathfindingLayer::LAND, srcNode->chainMask | CAST_CHAIN);
  226. if(nodeOptional)
  227. {
  228. #ifdef VCMI_TRACE_PATHFINDER
  229. logAi->trace("Adding town portal node at %s", targetTown->name);
  230. #endif
  231. AIPathNode * node = nodeOptional.value();
  232. node->theNodeBefore = source.node;
  233. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  234. node->moveRemains = source.node->moveRemains;
  235. neighbours.push_back(node);
  236. }
  237. }
  238. }
  239. }
  240. bool AINodeStorage::hasBetterChain(const PathNodeInfo & source, CDestinationNodeInfo & destination) const
  241. {
  242. auto pos = destination.coord;
  243. auto chains = nodes[EPathfindingLayer::LAND][pos.z][pos.x][pos.y];
  244. auto destinationNode = getAINode(destination.node);
  245. for(const AIPathNode & node : chains)
  246. {
  247. auto sameNode = node.chainMask == destinationNode->chainMask;
  248. if(sameNode || node.action == EPathNodeAction::UNKNOWN)
  249. {
  250. continue;
  251. }
  252. if(node.danger <= destinationNode->danger && destinationNode->chainMask == 1 && node.chainMask == 0)
  253. {
  254. if(node.getCost() < destinationNode->getCost())
  255. {
  256. #ifdef VCMI_TRACE_PATHFINDER
  257. logAi->trace(
  258. "Block inefficient move %s:->%s, mask=%i, mp diff: %i",
  259. source.coord.toString(),
  260. destination.coord.toString(),
  261. destinationNode->chainMask,
  262. node.moveRemains - destinationNode->moveRemains);
  263. #endif
  264. return true;
  265. }
  266. }
  267. }
  268. return false;
  269. }
  270. bool AINodeStorage::isTileAccessible(const int3 & pos, const EPathfindingLayer layer) const
  271. {
  272. return nodes[layer.getNum()][pos.z][pos.x][pos.y][0].action != EPathNodeAction::UNKNOWN;
  273. }
  274. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  275. {
  276. std::vector<AIPath> paths;
  277. auto chains = nodes[isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL][pos.z][pos.x][pos.y];
  278. auto initialPos = hero->visitablePos();
  279. for(const AIPathNode & node : chains)
  280. {
  281. if(node.action == EPathNodeAction::UNKNOWN)
  282. {
  283. continue;
  284. }
  285. AIPath path;
  286. const AIPathNode * current = &node;
  287. while(current != nullptr && current->coord != initialPos)
  288. {
  289. AIPathNodeInfo pathNode;
  290. pathNode.cost = current->getCost();
  291. pathNode.turns = current->turns;
  292. pathNode.danger = current->danger;
  293. pathNode.coord = current->coord;
  294. path.nodes.push_back(pathNode);
  295. path.specialAction = current->specialAction;
  296. current = getAINode(current->theNodeBefore);
  297. }
  298. path.targetObjectDanger = evaluateDanger(pos);
  299. paths.push_back(path);
  300. }
  301. return paths;
  302. }
  303. AIPath::AIPath()
  304. : nodes({})
  305. {
  306. }
  307. int3 AIPath::firstTileToGet() const
  308. {
  309. if(nodes.size())
  310. {
  311. return nodes.back().coord;
  312. }
  313. return int3(-1, -1, -1);
  314. }
  315. uint64_t AIPath::getPathDanger() const
  316. {
  317. if(nodes.size())
  318. {
  319. return nodes.front().danger;
  320. }
  321. return 0;
  322. }
  323. float AIPath::movementCost() const
  324. {
  325. if(nodes.size())
  326. {
  327. return nodes.front().cost;
  328. }
  329. // TODO: boost:optional?
  330. return 0.0;
  331. }
  332. uint64_t AIPath::getTotalDanger(HeroPtr hero) const
  333. {
  334. uint64_t pathDanger = getPathDanger();
  335. uint64_t danger = pathDanger > targetObjectDanger ? pathDanger : targetObjectDanger;
  336. return danger;
  337. }