2
0

AINodeStorage.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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, const CGHeroInstance * hero)
  27. {
  28. //TODO: fix this code duplication with NodeStorage::initialize, problem is to keep `resetTile` inline
  29. int3 pos;
  30. const int3 sizes = gs->getMapSize();
  31. const auto & fow = static_cast<const CGameInfoCallback *>(gs)->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.x=0; pos.x < sizes.x; ++pos.x)
  37. {
  38. for(pos.y=0; pos.y < sizes.y; ++pos.y)
  39. {
  40. for(pos.z=0; pos.z < sizes.z; ++pos.z)
  41. {
  42. const TerrainTile * tile = &gs->map->getTile(pos);
  43. switch(tile->terType)
  44. {
  45. case ETerrainType::ROCK:
  46. break;
  47. case ETerrainType::WATER:
  48. resetTile(pos, ELayer::SAIL, PathfinderUtil::evaluateAccessibility<ELayer::SAIL>(pos, tile, fow, player, gs));
  49. if(useFlying)
  50. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  51. if(useWaterWalking)
  52. resetTile(pos, ELayer::WATER, PathfinderUtil::evaluateAccessibility<ELayer::WATER>(pos, tile, fow, player, gs));
  53. break;
  54. default:
  55. resetTile(pos, ELayer::LAND, PathfinderUtil::evaluateAccessibility<ELayer::LAND>(pos, tile, fow, player, gs));
  56. if(useFlying)
  57. resetTile(pos, ELayer::AIR, PathfinderUtil::evaluateAccessibility<ELayer::AIR>(pos, tile, fow, player, gs));
  58. break;
  59. }
  60. }
  61. }
  62. }
  63. }
  64. const AIPathNode * AINodeStorage::getAINode(const CGPathNode * node) const
  65. {
  66. return static_cast<const AIPathNode *>(node);
  67. }
  68. void AINodeStorage::updateAINode(CGPathNode * node, std::function<void(AIPathNode *)> updater)
  69. {
  70. auto aiNode = static_cast<AIPathNode *>(node);
  71. updater(aiNode);
  72. }
  73. bool AINodeStorage::isBattleNode(const CGPathNode * node) const
  74. {
  75. return (getAINode(node)->chainMask & BATTLE_CHAIN) > 0;
  76. }
  77. boost::optional<AIPathNode *> AINodeStorage::getOrCreateNode(const int3 & pos, const EPathfindingLayer layer, int chainNumber)
  78. {
  79. auto chains = nodes[pos.x][pos.y][pos.z][layer];
  80. for(AIPathNode & node : chains)
  81. {
  82. if(node.chainMask == chainNumber)
  83. {
  84. return &node;
  85. }
  86. if(node.chainMask == 0)
  87. {
  88. node.chainMask = chainNumber;
  89. return &node;
  90. }
  91. }
  92. return boost::none;
  93. }
  94. CGPathNode * AINodeStorage::getInitialNode()
  95. {
  96. auto hpos = hero->getPosition(false);
  97. auto initialNode =
  98. getOrCreateNode(hpos, hero->boat ? EPathfindingLayer::SAIL : EPathfindingLayer::LAND, NORMAL_CHAIN)
  99. .get();
  100. initialNode->turns = 0;
  101. initialNode->moveRemains = hero->movement;
  102. initialNode->danger = 0;
  103. initialNode->setCost(0.0);
  104. return initialNode;
  105. }
  106. void AINodeStorage::resetTile(const int3 & coord, EPathfindingLayer layer, CGPathNode::EAccessibility accessibility)
  107. {
  108. for(int i = 0; i < NUM_CHAINS; i++)
  109. {
  110. AIPathNode & heroNode = nodes[coord.x][coord.y][coord.z][layer][i];
  111. heroNode.chainMask = 0;
  112. heroNode.danger = 0;
  113. heroNode.manaCost = 0;
  114. heroNode.specialAction.reset();
  115. heroNode.update(coord, layer, accessibility);
  116. }
  117. }
  118. void AINodeStorage::commit(CDestinationNodeInfo & destination, const PathNodeInfo & source)
  119. {
  120. const AIPathNode * srcNode = getAINode(source.node);
  121. updateAINode(destination.node, [&](AIPathNode * dstNode)
  122. {
  123. dstNode->moveRemains = destination.movementLeft;
  124. dstNode->turns = destination.turn;
  125. dstNode->setCost(destination.cost);
  126. dstNode->danger = srcNode->danger;
  127. dstNode->action = destination.action;
  128. dstNode->theNodeBefore = srcNode->theNodeBefore;
  129. dstNode->manaCost = srcNode->manaCost;
  130. if(dstNode->specialAction)
  131. {
  132. dstNode->specialAction->applyOnDestination(getHero(), destination, source, dstNode, srcNode);
  133. }
  134. });
  135. }
  136. std::vector<CGPathNode *> AINodeStorage::calculateNeighbours(
  137. const PathNodeInfo & source,
  138. const PathfinderConfig * pathfinderConfig,
  139. const CPathfinderHelper * pathfinderHelper)
  140. {
  141. std::vector<CGPathNode *> neighbours;
  142. neighbours.reserve(16);
  143. const AIPathNode * srcNode = getAINode(source.node);
  144. auto accessibleNeighbourTiles = pathfinderHelper->getNeighbourTiles(source);
  145. for(auto & neighbour : accessibleNeighbourTiles)
  146. {
  147. for(EPathfindingLayer i = EPathfindingLayer::LAND; i <= EPathfindingLayer::AIR; i.advance(1))
  148. {
  149. auto nextNode = getOrCreateNode(neighbour, i, srcNode->chainMask);
  150. if(!nextNode || nextNode.get()->accessible == CGPathNode::NOT_SET)
  151. continue;
  152. neighbours.push_back(nextNode.get());
  153. }
  154. }
  155. return neighbours;
  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.get());
  179. }
  180. }
  181. if(hero->getPosition(false) == 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. auto movementCost = GameConstants::BASE_MOVEMENT_COST * (skillLevel >= 3 ? 2 : 3);
  208. if(hero->movement < movementCost)
  209. {
  210. return;
  211. }
  212. if(skillLevel < SecSkillLevel::ADVANCED)
  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->visitingHero)
  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.get();
  231. node->theNodeBefore = source.node;
  232. node->specialAction.reset(new AIPathfinding::TownPortalAction(targetTown));
  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[pos.x][pos.y][pos.z][EPathfindingLayer::LAND];
  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 == CGPathNode::ENodeAction::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 ineficient 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. const AIPathNode & node = nodes[pos.x][pos.y][pos.z][layer][0];
  272. return node.action != CGPathNode::ENodeAction::UNKNOWN;
  273. }
  274. std::vector<AIPath> AINodeStorage::getChainInfo(const int3 & pos, bool isOnLand) const
  275. {
  276. std::vector<AIPath> paths;
  277. auto chains = nodes[pos.x][pos.y][pos.z][isOnLand ? EPathfindingLayer::LAND : EPathfindingLayer::SAIL];
  278. auto initialPos = hero->visitablePos();
  279. for(const AIPathNode & node : chains)
  280. {
  281. if(node.action == CGPathNode::ENodeAction::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. }