GraphPaths.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /*
  2. * GraphPaths.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 "GraphPaths.h"
  12. #include "AIPathfinderConfig.h"
  13. #include "../../../lib/CRandomGenerator.h"
  14. #include "../../../CCallback.h"
  15. #include "../../../lib/mapping/CMap.h"
  16. #include "../Engine/Nullkiller.h"
  17. #include "../../../lib/logging/VisualLogger.h"
  18. #include "Actions/QuestAction.h"
  19. #include "../pforeach.h"
  20. #include "Actions/BoatActions.h"
  21. namespace NKAI
  22. {
  23. bool GraphNodeComparer::operator()(const GraphPathNodePointer & lhs, const GraphPathNodePointer & rhs) const
  24. {
  25. return pathNodes.at(lhs.coord)[lhs.nodeType].cost > pathNodes.at(rhs.coord)[rhs.nodeType].cost;
  26. }
  27. GraphPaths::GraphPaths()
  28. : visualKey(""), graph(), pathNodes()
  29. {
  30. }
  31. std::shared_ptr<SpecialAction> getCompositeAction(
  32. const Nullkiller * ai,
  33. std::shared_ptr<ISpecialActionFactory> linkActionFactory,
  34. std::shared_ptr<SpecialAction> transitionAction)
  35. {
  36. if(!linkActionFactory)
  37. return transitionAction;
  38. auto linkAction = linkActionFactory->create(ai);
  39. if(!transitionAction)
  40. return linkAction;
  41. std::vector<std::shared_ptr<const SpecialAction>> actionsArray = {
  42. transitionAction,
  43. linkAction
  44. };
  45. return std::make_shared<CompositeAction>(actionsArray);
  46. }
  47. void GraphPaths::calculatePaths(const CGHeroInstance * targetHero, const Nullkiller * ai, uint8_t scanDepth)
  48. {
  49. graph.copyFrom(*ai->baseGraph);
  50. graph.connectHeroes(ai);
  51. visualKey = std::to_string(ai->playerID) + ":" + targetHero->getNameTranslated();
  52. pathNodes.clear();
  53. GraphNodeComparer cmp(pathNodes);
  54. GraphPathNode::TFibHeap pq(cmp);
  55. pathNodes[targetHero->visitablePos()][GrapthPathNodeType::NORMAL].cost = 0;
  56. pq.emplace(GraphPathNodePointer(targetHero->visitablePos(), GrapthPathNodeType::NORMAL));
  57. while(!pq.empty())
  58. {
  59. GraphPathNodePointer pos = pq.top();
  60. pq.pop();
  61. auto & node = getOrCreateNode(pos);
  62. std::shared_ptr<SpecialAction> transitionAction;
  63. if(node.obj)
  64. {
  65. if(node.obj->ID == Obj::QUEST_GUARD
  66. || node.obj->ID == Obj::BORDERGUARD
  67. || node.obj->ID == Obj::BORDER_GATE)
  68. {
  69. auto questObj = dynamic_cast<const IQuestObject *>(node.obj);
  70. auto questInfo = QuestInfo(questObj->quest, node.obj, pos.coord);
  71. if(node.obj->ID == Obj::QUEST_GUARD
  72. && questObj->quest->mission == Rewardable::Limiter{}
  73. && questObj->quest->killTarget == ObjectInstanceID::NONE)
  74. {
  75. continue;
  76. }
  77. auto questAction = std::make_shared<AIPathfinding::QuestAction>(questInfo);
  78. if(!questAction->canAct(ai, targetHero))
  79. {
  80. transitionAction = questAction;
  81. }
  82. }
  83. }
  84. node.isInQueue = false;
  85. graph.iterateConnections(pos.coord, [this, ai, &pos, &node, &transitionAction, &pq, scanDepth](int3 target, const ObjectLink & o)
  86. {
  87. auto compositeAction = getCompositeAction(ai, o.specialAction, transitionAction);
  88. auto targetNodeType = o.danger || compositeAction ? GrapthPathNodeType::BATTLE : pos.nodeType;
  89. auto targetPointer = GraphPathNodePointer(target, targetNodeType);
  90. auto & targetNode = getOrCreateNode(targetPointer);
  91. if(targetNode.tryUpdate(pos, node, o))
  92. {
  93. if(targetNode.cost > scanDepth)
  94. {
  95. return;
  96. }
  97. targetNode.specialAction = compositeAction;
  98. const auto & targetGraphNode = graph.getNode(target);
  99. if(targetGraphNode.objID.hasValue())
  100. {
  101. targetNode.obj = ai->cb->getObj(targetGraphNode.objID, false);
  102. if(targetNode.obj && targetNode.obj->ID == Obj::HERO)
  103. return;
  104. }
  105. if(targetNode.isInQueue)
  106. {
  107. pq.increase(targetNode.handle);
  108. }
  109. else
  110. {
  111. targetNode.handle = pq.emplace(targetPointer);
  112. targetNode.isInQueue = true;
  113. }
  114. }
  115. });
  116. }
  117. }
  118. void GraphPaths::dumpToLog() const
  119. {
  120. logVisual->updateWithLock(visualKey, [&](IVisualLogBuilder & logBuilder)
  121. {
  122. for(auto & tile : pathNodes)
  123. {
  124. for(auto & node : tile.second)
  125. {
  126. if(!node.previous.valid())
  127. continue;
  128. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  129. {
  130. logAi->trace(
  131. "%s -> %s: %f !%d",
  132. node.previous.coord.toString(),
  133. tile.first.toString(),
  134. node.cost,
  135. node.danger);
  136. }
  137. logBuilder.addLine(node.previous.coord, tile.first);
  138. }
  139. }
  140. });
  141. }
  142. bool GraphPathNode::tryUpdate(const GraphPathNodePointer & pos, const GraphPathNode & prev, const ObjectLink & link)
  143. {
  144. auto newCost = prev.cost + link.cost;
  145. if(newCost < cost)
  146. {
  147. previous = pos;
  148. danger = prev.danger + link.danger;
  149. cost = newCost;
  150. return true;
  151. }
  152. return false;
  153. }
  154. void GraphPaths::addChainInfo(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  155. {
  156. auto nodes = pathNodes.find(tile);
  157. if(nodes == pathNodes.end())
  158. return;
  159. for(auto & node : nodes->second)
  160. {
  161. if(!node.reachable())
  162. continue;
  163. std::vector<GraphPathNodePointer> tilesToPass;
  164. uint64_t danger = node.danger;
  165. float cost = node.cost;
  166. bool allowBattle = false;
  167. auto current = GraphPathNodePointer(nodes->first, node.nodeType);
  168. while(true)
  169. {
  170. auto currentTile = pathNodes.find(current.coord);
  171. if(currentTile == pathNodes.end())
  172. break;
  173. auto currentNode = currentTile->second[current.nodeType];
  174. if(!currentNode.previous.valid())
  175. break;
  176. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  177. vstd::amax(danger, currentNode.danger);
  178. vstd::amax(cost, currentNode.cost);
  179. tilesToPass.push_back(current);
  180. if(currentNode.cost < 2.0f)
  181. break;
  182. current = currentNode.previous;
  183. }
  184. if(tilesToPass.empty())
  185. continue;
  186. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  187. for(auto & path : entryPaths)
  188. {
  189. if(path.targetHero != hero)
  190. continue;
  191. for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  192. {
  193. AIPathNodeInfo n;
  194. n.coord = graphTile->coord;
  195. n.cost = cost;
  196. n.turns = static_cast<ui8>(cost) + 1; // just in case lets select worst scenario
  197. n.danger = danger;
  198. n.targetHero = hero;
  199. n.parentIndex = -1;
  200. n.specialAction = getNode(*graphTile).specialAction;
  201. if(n.specialAction)
  202. {
  203. n.actionIsBlocked = !n.specialAction->canAct(ai, n);
  204. }
  205. for(auto & node : path.nodes)
  206. {
  207. node.parentIndex++;
  208. }
  209. path.nodes.insert(path.nodes.begin(), n);
  210. }
  211. path.armyLoss += ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
  212. path.targetObjectDanger = ai->pathfinder->getStorage()->evaluateDanger(tile, path.targetHero, !allowBattle);
  213. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  214. paths.push_back(path);
  215. }
  216. }
  217. }
  218. void GraphPaths::quickAddChainInfoWithBlocker(std::vector<AIPath> & paths, int3 tile, const CGHeroInstance * hero, const Nullkiller * ai) const
  219. {
  220. auto nodes = pathNodes.find(tile);
  221. if(nodes == pathNodes.end())
  222. return;
  223. for(auto & targetNode : nodes->second)
  224. {
  225. if(!targetNode.reachable())
  226. continue;
  227. std::vector<GraphPathNodePointer> tilesToPass;
  228. uint64_t danger = targetNode.danger;
  229. float cost = targetNode.cost;
  230. bool allowBattle = false;
  231. auto current = GraphPathNodePointer(nodes->first, targetNode.nodeType);
  232. while(true)
  233. {
  234. auto currentTile = pathNodes.find(current.coord);
  235. if(currentTile == pathNodes.end())
  236. break;
  237. auto currentNode = currentTile->second[current.nodeType];
  238. allowBattle = allowBattle || currentNode.nodeType == GrapthPathNodeType::BATTLE;
  239. vstd::amax(danger, currentNode.danger);
  240. vstd::amax(cost, currentNode.cost);
  241. tilesToPass.push_back(current);
  242. if(currentNode.cost < 2.0f)
  243. break;
  244. current = currentNode.previous;
  245. }
  246. if(tilesToPass.empty())
  247. continue;
  248. auto entryPaths = ai->pathfinder->getPathInfo(tilesToPass.back().coord);
  249. for(auto & entryPath : entryPaths)
  250. {
  251. if(entryPath.targetHero != hero)
  252. continue;
  253. auto & path = paths.emplace_back();
  254. path.targetHero = entryPath.targetHero;
  255. path.heroArmy = entryPath.heroArmy;
  256. path.exchangeCount = entryPath.exchangeCount;
  257. path.armyLoss = entryPath.armyLoss + ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), danger);
  258. path.targetObjectDanger = ai->pathfinder->getStorage()->evaluateDanger(tile, path.targetHero, !allowBattle);
  259. path.targetObjectArmyLoss = ai->pathfinder->getStorage()->evaluateArmyLoss(path.targetHero, path.heroArmy->getArmyStrength(), path.targetObjectDanger);
  260. AIPathNodeInfo n;
  261. n.targetHero = hero;
  262. n.parentIndex = -1;
  263. // final node
  264. n.coord = tile;
  265. n.cost = targetNode.cost;
  266. n.danger = targetNode.danger;
  267. n.parentIndex = path.nodes.size();
  268. path.nodes.push_back(n);
  269. for(auto entryNode = entryPath.nodes.rbegin(); entryNode != entryPath.nodes.rend(); entryNode++)
  270. {
  271. auto blocker = ai->objectClusterizer->getBlocker(*entryNode);
  272. if(blocker)
  273. {
  274. // blocker node
  275. path.nodes.push_back(*entryNode);
  276. path.nodes.back().parentIndex = path.nodes.size() - 1;
  277. break;
  278. }
  279. }
  280. if(path.nodes.size() > 1)
  281. continue;
  282. for(auto graphTile = tilesToPass.rbegin(); graphTile != tilesToPass.rend(); graphTile++)
  283. {
  284. auto & node = getNode(*graphTile);
  285. n.coord = graphTile->coord;
  286. n.cost = node.cost;
  287. n.turns = static_cast<ui8>(node.cost);
  288. n.danger = node.danger;
  289. n.specialAction = node.specialAction;
  290. n.parentIndex = path.nodes.size();
  291. if(n.specialAction)
  292. {
  293. n.actionIsBlocked = !n.specialAction->canAct(ai, n);
  294. }
  295. auto blocker = ai->objectClusterizer->getBlocker(n);
  296. if(!blocker)
  297. continue;
  298. // blocker node
  299. path.nodes.push_back(n);
  300. break;
  301. }
  302. }
  303. }
  304. }
  305. }