ObjectClusterizer.cpp 8.6 KB

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