ObjectGraphCalculator.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. /*
  2. * ObjectGraphCalculator.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 "ObjectGraphCalculator.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. namespace NKAI
  21. {
  22. ObjectGraphCalculator::ObjectGraphCalculator(ObjectGraph * target, const Nullkiller * ai)
  23. :ai(ai), target(target), syncLock()
  24. {
  25. }
  26. void ObjectGraphCalculator::setGraphObjects()
  27. {
  28. for(auto obj : ai->memory->visitableObjs)
  29. {
  30. if(obj && obj->isVisitable() && obj->ID != Obj::HERO && obj->ID != Obj::EVENT)
  31. {
  32. addObjectActor(obj);
  33. }
  34. }
  35. for(auto town : ai->cb->getTownsInfo())
  36. {
  37. addObjectActor(town);
  38. }
  39. }
  40. void ObjectGraphCalculator::calculateConnections()
  41. {
  42. updatePaths();
  43. std::vector<AIPath> pathCache;
  44. foreach_tile_pos(ai->cb.get(), [this, &pathCache](const CPlayerSpecificInfoCallback * cb, const int3 & pos)
  45. {
  46. calculateConnections(pos, pathCache);
  47. });
  48. removeExtraConnections();
  49. }
  50. float ObjectGraphCalculator::getNeighborConnectionsCost(const int3 & pos, std::vector<AIPath> & pathCache)
  51. {
  52. float neighborCost = std::numeric_limits<float>::max();
  53. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  54. {
  55. logAi->trace("Checking junction %s", pos.toString());
  56. }
  57. foreach_neighbour(
  58. ai->cb.get(),
  59. pos,
  60. [this, &neighborCost, &pathCache](const CPlayerSpecificInfoCallback * cb, const int3 & neighbor)
  61. {
  62. ai->pathfinder->calculatePathInfo(pathCache, neighbor);
  63. auto costTotal = this->getConnectionsCost(pathCache);
  64. if(costTotal.connectionsCount > 2 && costTotal.avg < neighborCost)
  65. {
  66. neighborCost = costTotal.avg;
  67. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  68. {
  69. logAi->trace("Better node found at %s", neighbor.toString());
  70. }
  71. }
  72. });
  73. return neighborCost;
  74. }
  75. void ObjectGraphCalculator::addMinimalDistanceJunctions()
  76. {
  77. tbb::concurrent_unordered_set<int3, std::hash<int3>> junctions;
  78. pforeachTilePaths(ai->cb->getMapSize(), ai, [this, &junctions](const int3 & pos, std::vector<AIPath> & paths)
  79. {
  80. if(target->hasNodeAt(pos))
  81. return;
  82. if(ai->cb->getGuardingCreaturePosition(pos).valid())
  83. return;
  84. ConnectionCostInfo currentCost = getConnectionsCost(paths);
  85. if(currentCost.connectionsCount <= 2)
  86. return;
  87. float neighborCost = getNeighborConnectionsCost(pos, paths);
  88. if(currentCost.avg < neighborCost)
  89. {
  90. junctions.insert(pos);
  91. }
  92. });
  93. for(auto pos : junctions)
  94. {
  95. addJunctionActor(pos);
  96. }
  97. }
  98. void ObjectGraphCalculator::updatePaths()
  99. {
  100. PathfinderSettings ps;
  101. ps.mainTurnDistanceLimit = 5;
  102. ps.scoutTurnDistanceLimit = 1;
  103. ps.allowBypassObjects = false;
  104. ai->pathfinder->updatePaths(actors, ps);
  105. }
  106. void ObjectGraphCalculator::calculateConnections(const int3 & pos, std::vector<AIPath> & pathCache)
  107. {
  108. if(target->hasNodeAt(pos))
  109. {
  110. foreach_neighbour(
  111. ai->cb.get(),
  112. pos,
  113. [this, &pos, &pathCache](const CPlayerSpecificInfoCallback * cb, const int3 & neighbor)
  114. {
  115. if(target->hasNodeAt(neighbor))
  116. {
  117. ai->pathfinder->calculatePathInfo(pathCache, neighbor);
  118. for(auto & path : pathCache)
  119. {
  120. if(pos == path.targetHero->visitablePos())
  121. {
  122. target->tryAddConnection(pos, neighbor, path.movementCost(), path.getTotalDanger());
  123. }
  124. }
  125. }
  126. });
  127. auto obj = ai->cb->getTopObj(pos);
  128. if((obj && obj->ID == Obj::BOAT) || target->isVirtualBoat(pos))
  129. {
  130. ai->pathfinder->calculatePathInfo(pathCache, pos);
  131. for(AIPath & path : pathCache)
  132. {
  133. auto from = path.targetHero->visitablePos();
  134. auto fromObj = actorObjectMap[path.targetHero];
  135. auto danger = ai->pathfinder->getStorage()->evaluateDanger(pos, path.targetHero, true);
  136. auto updated = target->tryAddConnection(
  137. from,
  138. pos,
  139. path.movementCost(),
  140. danger);
  141. if(NKAI_GRAPH_TRACE_LEVEL >= 2 && updated)
  142. {
  143. logAi->trace(
  144. "Connected %s[%s] -> %s[%s] through [%s], cost %2f",
  145. fromObj ? fromObj->getObjectName() : "J", from.toString(),
  146. "Boat", pos.toString(),
  147. pos.toString(),
  148. path.movementCost());
  149. }
  150. }
  151. }
  152. return;
  153. }
  154. auto guardPos = ai->cb->getGuardingCreaturePosition(pos);
  155. ai->pathfinder->calculatePathInfo(pathCache, pos);
  156. for(AIPath & path1 : pathCache)
  157. {
  158. for(AIPath & path2 : pathCache)
  159. {
  160. if(path1.targetHero == path2.targetHero)
  161. continue;
  162. auto pos1 = path1.targetHero->visitablePos();
  163. auto pos2 = path2.targetHero->visitablePos();
  164. if(guardPos.valid() && guardPos != pos1 && guardPos != pos2)
  165. continue;
  166. auto obj1 = actorObjectMap[path1.targetHero];
  167. auto obj2 = actorObjectMap[path2.targetHero];
  168. auto tile1 = cb->getTile(pos1);
  169. auto tile2 = cb->getTile(pos2);
  170. if(tile2->isWater() && !tile1->isWater())
  171. {
  172. if(!cb->getTile(pos)->isWater())
  173. continue;
  174. auto startingObjIsBoat = (obj1 && obj1->ID == Obj::BOAT) || target->isVirtualBoat(pos1);
  175. if(!startingObjIsBoat)
  176. continue;
  177. }
  178. auto danger = ai->pathfinder->getStorage()->evaluateDanger(pos2, path1.targetHero, true);
  179. auto updated = target->tryAddConnection(
  180. pos1,
  181. pos2,
  182. path1.movementCost() + path2.movementCost(),
  183. danger);
  184. if(NKAI_GRAPH_TRACE_LEVEL >= 2 && updated)
  185. {
  186. logAi->trace(
  187. "Connected %s[%s] -> %s[%s] through [%s], cost %2f",
  188. obj1 ? obj1->getObjectName() : "J", pos1.toString(),
  189. obj2 ? obj2->getObjectName() : "J", pos2.toString(),
  190. pos.toString(),
  191. path1.movementCost() + path2.movementCost());
  192. }
  193. }
  194. }
  195. }
  196. bool ObjectGraphCalculator::isExtraConnection(float direct, float side1, float side2) const
  197. {
  198. float sideRatio = (side1 + side2) / direct;
  199. return sideRatio < 1.25f && direct > side1 && direct > side2;
  200. }
  201. void ObjectGraphCalculator::removeExtraConnections()
  202. {
  203. std::vector<std::pair<int3, int3>> connectionsToRemove;
  204. for(auto & actor : temporaryActorHeroes)
  205. {
  206. auto pos = actor->visitablePos();
  207. auto & currentNode = target->getNode(pos);
  208. target->iterateConnections(pos, [this, &pos, &connectionsToRemove, &currentNode](int3 n1, ObjectLink o1)
  209. {
  210. target->iterateConnections(n1, [&pos, &o1, &currentNode, &connectionsToRemove, this](int3 n2, ObjectLink o2)
  211. {
  212. auto direct = currentNode.connections.find(n2);
  213. if(direct != currentNode.connections.end() && isExtraConnection(direct->second.cost, o1.cost, o2.cost))
  214. {
  215. connectionsToRemove.push_back({pos, n2});
  216. }
  217. });
  218. });
  219. }
  220. vstd::removeDuplicates(connectionsToRemove);
  221. for(auto & c : connectionsToRemove)
  222. {
  223. target->removeConnection(c.first, c.second);
  224. if(NKAI_GRAPH_TRACE_LEVEL >= 2)
  225. {
  226. logAi->trace("Remove ineffective connection %s->%s", c.first.toString(), c.second.toString());
  227. }
  228. }
  229. }
  230. void ObjectGraphCalculator::addObjectActor(const CGObjectInstance * obj)
  231. {
  232. auto objectActor = temporaryActorHeroes.emplace_back(std::make_unique<CGHeroInstance>(obj->cb)).get();
  233. CRandomGenerator rng;
  234. auto visitablePos = obj->visitablePos();
  235. objectActor->setOwner(ai->playerID); // lets avoid having multiple colors
  236. objectActor->initHero(rng, static_cast<HeroTypeID>(0));
  237. objectActor->pos = objectActor->convertFromVisitablePos(visitablePos);
  238. objectActor->initObj(rng);
  239. if(cb->getTile(visitablePos)->isWater())
  240. {
  241. objectActor->boat = temporaryBoats.emplace_back(std::make_unique<CGBoat>(objectActor->cb)).get();
  242. }
  243. assert(objectActor->visitablePos() == visitablePos);
  244. actorObjectMap[objectActor] = obj;
  245. actors[objectActor] = obj->ID == Obj::TOWN || obj->ID == Obj::BOAT ? HeroRole::MAIN : HeroRole::SCOUT;
  246. target->addObject(obj);
  247. auto shipyard = dynamic_cast<const IShipyard *>(obj);
  248. if(shipyard && shipyard->bestLocation().valid())
  249. {
  250. int3 virtualBoat = shipyard->bestLocation();
  251. addJunctionActor(virtualBoat, true);
  252. target->addVirtualBoat(virtualBoat, obj);
  253. }
  254. }
  255. void ObjectGraphCalculator::addJunctionActor(const int3 & visitablePos, bool isVirtualBoat)
  256. {
  257. std::lock_guard lock(syncLock);
  258. auto internalCb = temporaryActorHeroes.front()->cb;
  259. auto objectActor = temporaryActorHeroes.emplace_back(std::make_unique<CGHeroInstance>(internalCb)).get();
  260. CRandomGenerator rng;
  261. objectActor->setOwner(ai->playerID); // lets avoid having multiple colors
  262. objectActor->initHero(rng, static_cast<HeroTypeID>(0));
  263. objectActor->pos = objectActor->convertFromVisitablePos(visitablePos);
  264. objectActor->initObj(rng);
  265. if(isVirtualBoat || ai->cb->getTile(visitablePos)->isWater())
  266. {
  267. objectActor->boat = temporaryBoats.emplace_back(std::make_unique<CGBoat>(objectActor->cb)).get();
  268. }
  269. assert(objectActor->visitablePos() == visitablePos);
  270. actorObjectMap[objectActor] = nullptr;
  271. actors[objectActor] = isVirtualBoat ? HeroRole::MAIN : HeroRole::SCOUT;
  272. target->registerJunction(visitablePos);
  273. }
  274. ConnectionCostInfo ObjectGraphCalculator::getConnectionsCost(std::vector<AIPath> & paths) const
  275. {
  276. std::map<int3, float> costs;
  277. for(auto & path : paths)
  278. {
  279. auto fromPos = path.targetHero->visitablePos();
  280. auto cost = costs.find(fromPos);
  281. if(cost == costs.end())
  282. {
  283. costs.emplace(fromPos, path.movementCost());
  284. }
  285. else
  286. {
  287. if(path.movementCost() < cost->second)
  288. {
  289. costs[fromPos] = path.movementCost();
  290. }
  291. }
  292. }
  293. ConnectionCostInfo result;
  294. for(auto & cost : costs)
  295. {
  296. result.totalCost += cost.second;
  297. result.connectionsCount++;
  298. }
  299. if(result.connectionsCount)
  300. {
  301. result.avg = result.totalCost / result.connectionsCount;
  302. }
  303. return result;
  304. }
  305. }