ObjectClusterizer.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. * DangerHitMapAnalyzer.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 "ObjectClusterizer.h"
  12. #include "../Goals/ExecuteHeroChain.h"
  13. #include "../AIGateway.h"
  14. #include "../Engine/Nullkiller.h"
  15. namespace NKAI
  16. {
  17. void ObjectCluster::addObject(const CGObjectInstance * obj, const AIPath & path, float priority)
  18. {
  19. ClusterObjects::accessor info;
  20. objects.insert(info, ClusterObjects::value_type(obj, ClusterObjectInfo()));
  21. if(info->second.priority < priority)
  22. {
  23. info->second.priority = priority;
  24. info->second.movementCost = path.movementCost() - path.firstNode().cost;
  25. info->second.danger = path.targetObjectDanger;
  26. info->second.turn = path.turn();
  27. }
  28. }
  29. const CGObjectInstance * ObjectCluster::calculateCenter() const
  30. {
  31. auto v = getObjects();
  32. auto tile = int3(0);
  33. float priority = 0;
  34. for(auto pair : objects)
  35. {
  36. auto newPoint = pair.first->visitablePos();
  37. float newPriority = std::pow(pair.second.priority, 4); // lets make high priority targets more weghtful
  38. int3 direction = newPoint - tile;
  39. float priorityRatio = newPriority / (priority + newPriority);
  40. tile += direction * priorityRatio;
  41. priority += newPriority;
  42. }
  43. auto closestPair = *vstd::minElementByFun(objects, [&](const std::pair<const CGObjectInstance *, ClusterObjectInfo> & pair) -> int
  44. {
  45. return pair.first->visitablePos().dist2dSQ(tile);
  46. });
  47. return closestPair.first;
  48. }
  49. std::vector<const CGObjectInstance *> ObjectCluster::getObjects() const
  50. {
  51. std::vector<const CGObjectInstance *> result;
  52. for(auto pair : objects)
  53. {
  54. result.push_back(pair.first);
  55. }
  56. return result;
  57. }
  58. std::vector<const CGObjectInstance *> ObjectClusterizer::getNearbyObjects() const
  59. {
  60. return nearObjects.getObjects();
  61. }
  62. std::vector<const CGObjectInstance *> ObjectClusterizer::getFarObjects() const
  63. {
  64. return farObjects.getObjects();
  65. }
  66. std::vector<std::shared_ptr<ObjectCluster>> ObjectClusterizer::getLockedClusters() const
  67. {
  68. std::vector<std::shared_ptr<ObjectCluster>> result;
  69. for(auto pair : blockedObjects)
  70. {
  71. result.push_back(pair.second);
  72. }
  73. return result;
  74. }
  75. const CGObjectInstance * ObjectClusterizer::getBlocker(const AIPath & path) const
  76. {
  77. for(auto node = path.nodes.rbegin(); node != path.nodes.rend(); node++)
  78. {
  79. auto guardPos = ai->cb->getGuardingCreaturePosition(node->coord);
  80. auto blockers = ai->cb->getVisitableObjs(node->coord);
  81. if(guardPos.valid())
  82. {
  83. auto guard = ai->cb->getTopObj(ai->cb->getGuardingCreaturePosition(node->coord));
  84. if(guard)
  85. {
  86. blockers.insert(blockers.begin(), guard);
  87. }
  88. }
  89. if(node->specialAction && node->actionIsBlocked)
  90. {
  91. auto blockerObject = node->specialAction->targetObject();
  92. if(blockerObject)
  93. {
  94. blockers.insert(blockers.begin(), blockerObject);
  95. }
  96. }
  97. if(blockers.empty())
  98. continue;
  99. auto blocker = blockers.front();
  100. if(isObjectPassable(ai, blocker))
  101. continue;
  102. if(blocker->ID == Obj::GARRISON
  103. || blocker->ID == Obj::GARRISON2)
  104. {
  105. if(dynamic_cast<const CArmedInstance *>(blocker)->getArmyStrength() == 0)
  106. continue;
  107. else
  108. return blocker;
  109. }
  110. if(blocker->ID == Obj::MONSTER
  111. || blocker->ID == Obj::BORDERGUARD
  112. || blocker->ID == Obj::BORDER_GATE
  113. || blocker->ID == Obj::SHIPYARD
  114. || (blocker->ID == Obj::QUEST_GUARD && node->actionIsBlocked))
  115. {
  116. return blocker;
  117. }
  118. }
  119. return nullptr;
  120. }
  121. bool ObjectClusterizer::shouldVisitObject(const CGObjectInstance * obj) const
  122. {
  123. if(isObjectRemovable(obj))
  124. {
  125. return true;
  126. }
  127. const int3 pos = obj->visitablePos();
  128. if((obj->ID != Obj::CREATURE_GENERATOR1 && vstd::contains(ai->memory->alreadyVisited, obj))
  129. || obj->wasVisited(ai->playerID))
  130. {
  131. return false;
  132. }
  133. auto playerRelations = ai->cb->getPlayerRelations(ai->playerID, obj->tempOwner);
  134. if(playerRelations != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
  135. {
  136. return false;
  137. }
  138. //it may be hero visiting this obj
  139. //we don't try visiting object on which allied or owned hero stands
  140. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  141. const CGObjectInstance * topObj = ai->cb->getTopObj(pos);
  142. if(!topObj)
  143. return false; // partly visible obj but its visitable pos is not visible.
  144. if(topObj->ID == Obj::HERO && ai->cb->getPlayerRelations(ai->playerID, topObj->tempOwner) != PlayerRelations::ENEMIES)
  145. return false;
  146. else
  147. return true; //all of the following is met
  148. }
  149. void ObjectClusterizer::clusterize()
  150. {
  151. auto start = std::chrono::high_resolution_clock::now();
  152. nearObjects.reset();
  153. farObjects.reset();
  154. blockedObjects.clear();
  155. Obj ignoreObjects[] = {
  156. Obj::BOAT,
  157. Obj::EYE_OF_MAGI,
  158. Obj::MONOLITH_ONE_WAY_ENTRANCE,
  159. Obj::MONOLITH_ONE_WAY_EXIT,
  160. Obj::MONOLITH_TWO_WAY,
  161. Obj::SUBTERRANEAN_GATE,
  162. Obj::WHIRLPOOL,
  163. Obj::BUOY,
  164. Obj::SIGN,
  165. Obj::GARRISON,
  166. Obj::MONSTER,
  167. Obj::GARRISON2,
  168. Obj::BORDERGUARD,
  169. Obj::QUEST_GUARD,
  170. Obj::BORDER_GATE,
  171. Obj::REDWOOD_OBSERVATORY,
  172. Obj::CARTOGRAPHER,
  173. Obj::PILLAR_OF_FIRE
  174. };
  175. logAi->debug("Begin object clusterization");
  176. std::vector<const CGObjectInstance *> objs(
  177. ai->memory->visitableObjs.begin(),
  178. ai->memory->visitableObjs.end());
  179. parallel_for(blocked_range<size_t>(0, objs.size()), [&](const blocked_range<size_t> & r)
  180. {
  181. auto priorityEvaluator = ai->priorityEvaluators->acquire();
  182. for(int i = r.begin(); i != r.end(); i++)
  183. {
  184. auto obj = objs[i];
  185. if(!shouldVisitObject(obj))
  186. {
  187. #if NKAI_TRACE_LEVEL >= 2
  188. logAi->trace("Skip object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
  189. #endif
  190. continue;
  191. }
  192. #if NKAI_TRACE_LEVEL >= 2
  193. logAi->trace("Check object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
  194. #endif
  195. auto paths = ai->pathfinder->getPathInfo(obj->visitablePos());
  196. if(paths.empty())
  197. {
  198. #if NKAI_TRACE_LEVEL >= 2
  199. logAi->trace("No paths found.");
  200. #endif
  201. continue;
  202. }
  203. std::sort(paths.begin(), paths.end(), [](const AIPath & p1, const AIPath & p2) -> bool
  204. {
  205. return p1.movementCost() < p2.movementCost();
  206. });
  207. if(vstd::contains(ignoreObjects, obj->ID))
  208. {
  209. farObjects.addObject(obj, paths.front(), 0);
  210. #if NKAI_TRACE_LEVEL >= 2
  211. logAi->trace("Object ignored. Moved to far objects with path %s", paths.front().toString());
  212. #endif
  213. continue;
  214. }
  215. std::set<const CGHeroInstance *> heroesProcessed;
  216. for(auto & path : paths)
  217. {
  218. #if NKAI_TRACE_LEVEL >= 2
  219. logAi->trace("Checking path %s", path.toString());
  220. #endif
  221. if(!shouldVisit(ai, path.targetHero, obj))
  222. {
  223. #if NKAI_TRACE_LEVEL >= 2
  224. logAi->trace("Hero %s does not need to visit %s", path.targetHero->getObjectName(), obj->getObjectName());
  225. #endif
  226. continue;
  227. }
  228. if(path.nodes.size() > 1)
  229. {
  230. auto blocker = getBlocker(path);
  231. if(blocker)
  232. {
  233. if(vstd::contains(heroesProcessed, path.targetHero))
  234. {
  235. #if NKAI_TRACE_LEVEL >= 2
  236. logAi->trace("Hero %s is already processed.", path.targetHero->getObjectName());
  237. #endif
  238. continue;
  239. }
  240. heroesProcessed.insert(path.targetHero);
  241. float priority = priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)));
  242. if(priority < MIN_PRIORITY)
  243. continue;
  244. ClusterMap::accessor cluster;
  245. blockedObjects.insert(
  246. cluster,
  247. ClusterMap::value_type(blocker, std::make_shared<ObjectCluster>(blocker)));
  248. cluster->second->addObject(obj, path, priority);
  249. #if NKAI_TRACE_LEVEL >= 2
  250. logAi->trace("Path added to cluster %s%s", blocker->getObjectName(), blocker->visitablePos().toString());
  251. #endif
  252. continue;
  253. }
  254. }
  255. heroesProcessed.insert(path.targetHero);
  256. float priority = priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)));
  257. if(priority < MIN_PRIORITY)
  258. continue;
  259. bool interestingObject = path.turn() <= 2 || priority > 0.5f;
  260. if(interestingObject)
  261. {
  262. nearObjects.addObject(obj, path, priority);
  263. }
  264. else
  265. {
  266. farObjects.addObject(obj, path, priority);
  267. }
  268. #if NKAI_TRACE_LEVEL >= 2
  269. logAi->trace("Path %s added to %s objects. Turn: %d, priority: %f",
  270. path.toString(),
  271. interestingObject ? "near" : "far",
  272. path.turn(),
  273. priority);
  274. #endif
  275. }
  276. }
  277. });
  278. logAi->trace("Near objects count: %i", nearObjects.objects.size());
  279. logAi->trace("Far objects count: %i", farObjects.objects.size());
  280. for(auto pair : blockedObjects)
  281. {
  282. logAi->trace("Cluster %s %s count: %i", pair.first->getObjectName(), pair.first->visitablePos().toString(), pair.second->objects.size());
  283. #if NKAI_TRACE_LEVEL >= 1
  284. for(auto obj : pair.second->getObjects())
  285. {
  286. logAi->trace("Object %s %s", obj->getObjectName(), obj->visitablePos().toString());
  287. }
  288. #endif
  289. }
  290. logAi->trace("Clusterization complete in %ld", timeElapsed(start));
  291. }
  292. }