ObjectClusterizer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 NK2AI
  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->id, 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 CPlayerSpecificInfoCallback * cpsic) const
  30. {
  31. auto tile = int3(0);
  32. float priority = 0;
  33. for(auto & pair : objects)
  34. {
  35. auto newPoint = cpsic->getObj(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<ObjectInstanceID, ClusterObjectInfo> & pair) -> int
  43. {
  44. return cpsic->getObj(pair.first)->visitablePos().dist2dSQ(tile);
  45. });
  46. return cpsic->getObj(closestPair.first);
  47. }
  48. std::vector<const CGObjectInstance *> ObjectCluster::getObjects(const CPlayerSpecificInfoCallback * cpsic) const
  49. {
  50. std::vector<const CGObjectInstance *> result;
  51. for(auto & pair : objects)
  52. {
  53. result.push_back(cpsic->getObj(pair.first));
  54. }
  55. return result;
  56. }
  57. std::vector<const CGObjectInstance *> ObjectClusterizer::getNearbyObjects() const
  58. {
  59. return nearObjects.getObjects(aiNk->cc.get());
  60. }
  61. std::vector<const CGObjectInstance *> ObjectClusterizer::getFarObjects() const
  62. {
  63. return farObjects.getObjects(aiNk->cc.get());
  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. std::optional<const CGObjectInstance *> ObjectClusterizer::getBlocker(const AIPathNodeInfo & node) const
  75. {
  76. std::vector<const CGObjectInstance *> blockers = {};
  77. if(node.layer == EPathfindingLayer::LAND || node.layer == EPathfindingLayer::SAIL)
  78. {
  79. auto guardPos = aiNk->cc->getGuardingCreaturePosition(node.coord);
  80. if (aiNk->cc->isVisible(node.coord))
  81. blockers = aiNk->cc->getVisitableObjs(node.coord);
  82. if(guardPos.isValid() && aiNk->cc->isVisible(guardPos))
  83. {
  84. auto guard = aiNk->cc->getTopObj(aiNk->cc->getGuardingCreaturePosition(node.coord));
  85. if(guard)
  86. {
  87. blockers.insert(blockers.begin(), guard);
  88. }
  89. }
  90. }
  91. if(node.specialAction && node.actionIsBlocked)
  92. {
  93. auto blockerObject = node.specialAction->targetObject();
  94. if(blockerObject)
  95. {
  96. blockers.insert(blockers.begin(), blockerObject);
  97. }
  98. }
  99. if(blockers.empty())
  100. return std::optional< const CGObjectInstance *>();
  101. auto blocker = blockers.front();
  102. if(isObjectPassable(aiNk, blocker))
  103. return std::optional< const CGObjectInstance *>();
  104. if(blocker->ID == Obj::GARRISON
  105. || blocker->ID == Obj::GARRISON2)
  106. {
  107. if(dynamic_cast<const CArmedInstance *>(blocker)->getArmyStrength() == 0)
  108. return std::optional< const CGObjectInstance *>();
  109. else
  110. return blocker;
  111. }
  112. if(blocker->ID == Obj::MONSTER
  113. || blocker->ID == Obj::BORDERGUARD
  114. || blocker->ID == Obj::BORDER_GATE
  115. || blocker->ID == Obj::SHIPYARD
  116. || (blocker->ID == Obj::QUEST_GUARD && node.actionIsBlocked))
  117. {
  118. return blocker;
  119. }
  120. auto danger = aiNk->dangerEvaluator->evaluateDanger(blocker);
  121. if(danger > 0 && blocker->isBlockedVisitable() && isObjectRemovable(blocker))
  122. {
  123. return blocker;
  124. }
  125. return std::optional< const CGObjectInstance *>();
  126. }
  127. const CGObjectInstance * ObjectClusterizer::getBlocker(const AIPath & path) const
  128. {
  129. for(auto node = path.nodes.rbegin(); node != path.nodes.rend(); node++)
  130. {
  131. auto blocker = getBlocker(*node);
  132. if(blocker)
  133. return *blocker;
  134. }
  135. return nullptr;
  136. }
  137. void ObjectClusterizer::invalidate(ObjectInstanceID id)
  138. {
  139. nearObjects.objects.erase(id);
  140. farObjects.objects.erase(id);
  141. invalidated.push_back(id);
  142. for(auto & c : blockedObjects)
  143. {
  144. c.second->objects.erase(id);
  145. }
  146. }
  147. void ObjectClusterizer::validateObjects()
  148. {
  149. std::vector<ObjectInstanceID> toRemove;
  150. auto scanRemovedObjects = [this, &toRemove](const ObjectCluster & cluster)
  151. {
  152. for(auto & pair : cluster.objects)
  153. {
  154. if(!aiNk->cc->getObj(pair.first, false))
  155. toRemove.push_back(pair.first);
  156. }
  157. };
  158. scanRemovedObjects(nearObjects);
  159. scanRemovedObjects(farObjects);
  160. for(auto & pair : blockedObjects)
  161. {
  162. if(!aiNk->cc->getObj(pair.first, false) || pair.second->objects.empty())
  163. toRemove.push_back(pair.first);
  164. else
  165. scanRemovedObjects(*pair.second);
  166. }
  167. vstd::removeDuplicates(toRemove);
  168. for(auto id : toRemove)
  169. {
  170. onObjectRemoved(id);
  171. }
  172. }
  173. void ObjectClusterizer::onObjectRemoved(ObjectInstanceID id)
  174. {
  175. invalidate(id);
  176. vstd::erase_if_present(invalidated, id);
  177. NK2AI::ClusterMap::accessor cluster;
  178. if(blockedObjects.find(cluster, id))
  179. {
  180. for(auto & unlocked : cluster->second->objects)
  181. {
  182. invalidated.push_back(unlocked.first);
  183. }
  184. blockedObjects.erase(cluster);
  185. }
  186. }
  187. bool ObjectClusterizer::shouldVisitObject(const CGObjectInstance * obj) const
  188. {
  189. if(isObjectRemovable(obj))
  190. {
  191. return true;
  192. }
  193. const int3 pos = obj->visitablePos();
  194. if((obj->ID != Obj::CREATURE_GENERATOR1 && vstd::contains(aiNk->memory->alreadyVisited, obj))
  195. || obj->wasVisited(aiNk->playerID))
  196. {
  197. return false;
  198. }
  199. auto playerRelations = aiNk->cc->getPlayerRelations(aiNk->playerID, obj->tempOwner);
  200. if(playerRelations != PlayerRelations::ENEMIES && !isWeeklyRevisitable(aiNk->playerID, obj))
  201. {
  202. return false;
  203. }
  204. //it may be hero visiting this obj
  205. //we don't try visiting object on which allied or owned hero stands
  206. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  207. const CGObjectInstance * topObj = aiNk->cc->getTopObj(pos);
  208. if(!topObj)
  209. return false; // partly visible obj but its visitable pos is not visible.
  210. if(topObj->ID == Obj::HERO && aiNk->cc->getPlayerRelations(aiNk->playerID, topObj->tempOwner) != PlayerRelations::ENEMIES)
  211. return false;
  212. else
  213. return true; //all of the following is met
  214. }
  215. Obj ObjectClusterizer::IgnoredObjectTypes[] = {
  216. Obj::BOAT,
  217. Obj::EYE_OF_MAGI,
  218. Obj::MONOLITH_ONE_WAY_ENTRANCE,
  219. Obj::MONOLITH_ONE_WAY_EXIT,
  220. Obj::MONOLITH_TWO_WAY,
  221. Obj::SUBTERRANEAN_GATE,
  222. Obj::WHIRLPOOL,
  223. Obj::BUOY,
  224. Obj::SIGN,
  225. Obj::GARRISON,
  226. Obj::MONSTER,
  227. Obj::GARRISON2,
  228. Obj::BORDERGUARD,
  229. Obj::QUEST_GUARD,
  230. Obj::BORDER_GATE,
  231. Obj::REDWOOD_OBSERVATORY,
  232. Obj::CARTOGRAPHER,
  233. Obj::PILLAR_OF_FIRE
  234. };
  235. void ObjectClusterizer::clusterize()
  236. {
  237. if(isUpToDate)
  238. {
  239. validateObjects();
  240. }
  241. if(isUpToDate && invalidated.empty())
  242. return;
  243. auto start = std::chrono::high_resolution_clock::now();
  244. logAi->debug("Begin object clusterization");
  245. std::vector<const CGObjectInstance *> objs;
  246. if(isUpToDate)
  247. {
  248. for(auto id : invalidated)
  249. {
  250. auto obj = ccTl->getObj(id, false);
  251. if(obj)
  252. {
  253. objs.push_back(obj);
  254. }
  255. }
  256. invalidated.clear();
  257. }
  258. else
  259. {
  260. nearObjects.reset();
  261. farObjects.reset();
  262. blockedObjects.clear();
  263. invalidated.clear();
  264. objs = std::vector<const CGObjectInstance *>(
  265. aiNk->memory->visitableObjs.begin(),
  266. aiNk->memory->visitableObjs.end());
  267. }
  268. tbb::parallel_for(
  269. tbb::blocked_range<size_t>(0, objs.size()),
  270. [&](const tbb::blocked_range<size_t> & r)
  271. {
  272. SET_GLOBAL_STATE_TBB(aiNk->aiGw);
  273. auto priorityEvaluator = aiNk->priorityEvaluators->acquire();
  274. auto heroes = aiNk->cc->getHeroesInfo();
  275. std::vector<AIPath> pathCache;
  276. for(int i = r.begin(); i != r.end(); i++)
  277. {
  278. clusterizeObject(objs[i], priorityEvaluator.get(), pathCache, heroes);
  279. }
  280. }
  281. );
  282. logAi->trace("Near objects count: %i", nearObjects.objects.size());
  283. logAi->trace("Far objects count: %i", farObjects.objects.size());
  284. for(auto pair : blockedObjects)
  285. {
  286. auto blocker = ccTl->getObj(pair.first);
  287. logAi->trace("Cluster %s %s count: %i", blocker->getObjectName(), blocker->visitablePos().toString(), pair.second->objects.size());
  288. #if NK2AI_TRACE_LEVEL >= 1
  289. for(auto obj : pair.second->getObjects(aiNk->cc.get()))
  290. {
  291. logAi->trace("Object %s %s", obj->getObjectName(), obj->visitablePos().toString());
  292. }
  293. #endif
  294. }
  295. isUpToDate = true;
  296. logAi->trace("Clusterization complete in %ld", timeElapsed(start));
  297. }
  298. void ObjectClusterizer::clusterizeObject(
  299. const CGObjectInstance * obj,
  300. PriorityEvaluator * priorityEvaluator,
  301. std::vector<AIPath> & pathCache,
  302. std::vector<const CGHeroInstance *> & heroes)
  303. {
  304. if(!shouldVisitObject(obj))
  305. {
  306. #if NK2AI_TRACE_LEVEL >= 2
  307. logAi->trace("Skip object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
  308. #endif
  309. return;
  310. }
  311. #if NK2AI_TRACE_LEVEL >= 2
  312. logAi->trace("Check object %s%s.", obj->getObjectName(), obj->visitablePos().toString());
  313. #endif
  314. if(aiNk->isObjectGraphAllowed())
  315. {
  316. aiNk->pathfinder->calculateQuickPathsWithBlocker(pathCache, heroes, obj->visitablePos());
  317. }
  318. else
  319. aiNk->pathfinder->calculatePathInfo(pathCache, obj->visitablePos(), false);
  320. if(pathCache.empty())
  321. {
  322. #if NK2AI_TRACE_LEVEL >= 2
  323. logAi->trace("No paths found.");
  324. #endif
  325. return;
  326. }
  327. std::sort(pathCache.begin(), pathCache.end(), [](const AIPath & p1, const AIPath & p2) -> bool
  328. {
  329. return p1.movementCost() < p2.movementCost();
  330. });
  331. if(vstd::contains(IgnoredObjectTypes, obj->ID))
  332. {
  333. farObjects.addObject(obj, pathCache.front(), 0);
  334. #if NK2AI_TRACE_LEVEL >= 2
  335. logAi->trace("Object ignored. Moved to far objects with path %s", pathCache.front().toString());
  336. #endif
  337. return;
  338. }
  339. std::set<const CGHeroInstance *> heroesProcessed;
  340. for(auto & path : pathCache)
  341. {
  342. #if NK2AI_TRACE_LEVEL >= 2
  343. logAi->trace("ObjectClusterizer Checking path %s", path.toString());
  344. #endif
  345. if(aiNk->heroManager->getHeroRole(HeroPtr(path.targetHero)) == HeroRole::SCOUT)
  346. {
  347. // TODO: Mircea: Shouldn't this be linked with scoutHeroTurnDistanceLimit?
  348. // TODO: Mircea: Move to constant
  349. // if(path.movementCost() > 2.0f)
  350. if(path.movementCost() > aiNk->settings->getScoutHeroTurnDistanceLimit())
  351. {
  352. #if NK2AI_TRACE_LEVEL >= 2
  353. logAi->trace("Path is too far %f", path.movementCost());
  354. #endif
  355. continue;
  356. }
  357. }
  358. // TODO: Mircea: Move to constant
  359. else if(path.movementCost() > 4.0f && obj->ID != Obj::TOWN)
  360. {
  361. auto strategicalValue = valueEvaluator.getStrategicalValue(obj);
  362. if(strategicalValue < MINIMUM_STRATEGICAL_VALUE_NON_TOWN)
  363. {
  364. #if NK2AI_TRACE_LEVEL >= 2
  365. logAi->trace("Object value is too low %f", strategicalValue);
  366. #endif
  367. continue;
  368. }
  369. }
  370. if(!shouldVisit(aiNk, path.targetHero, obj))
  371. {
  372. #if NK2AI_TRACE_LEVEL >= 2
  373. logAi->trace("Hero %s shouldn't visit %s", path.targetHero->getObjectName(), obj->getObjectName());
  374. #endif
  375. continue;
  376. }
  377. float priority = 0;
  378. if(path.nodes.size() > 1)
  379. {
  380. auto blocker = getBlocker(path);
  381. if(blocker)
  382. {
  383. if(vstd::contains(heroesProcessed, path.targetHero))
  384. {
  385. #if NK2AI_TRACE_LEVEL >= 2
  386. logAi->trace("Hero %s is already processed.", path.targetHero->getObjectName());
  387. #endif
  388. continue;
  389. }
  390. heroesProcessed.insert(path.targetHero);
  391. for (int prio = PriorityEvaluator::PriorityTier::BUILDINGS; prio <= PriorityEvaluator::PriorityTier::MAX_PRIORITY_TIER; ++prio)
  392. {
  393. priority = std::max(priority, priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)), prio));
  394. }
  395. if(aiNk->settings->isUseFuzzy() && priority < MIN_PRIORITY)
  396. continue;
  397. if (priority <= 0)
  398. continue;
  399. ClusterMap::accessor cluster;
  400. blockedObjects.insert(
  401. cluster,
  402. ClusterMap::value_type(blocker->id, std::make_shared<ObjectCluster>(blocker)));
  403. cluster->second->addObject(obj, path, priority);
  404. #if NK2AI_TRACE_LEVEL >= 2
  405. logAi->trace("Path added to cluster %s%s", blocker->getObjectName(), blocker->visitablePos().toString());
  406. #endif
  407. continue;
  408. }
  409. }
  410. heroesProcessed.insert(path.targetHero);
  411. for (int prio = PriorityEvaluator::PriorityTier::BUILDINGS; prio <= PriorityEvaluator::PriorityTier::MAX_PRIORITY_TIER; ++prio)
  412. {
  413. priority = std::max(priority, priorityEvaluator->evaluate(Goals::sptr(Goals::ExecuteHeroChain(path, obj)), prio));
  414. }
  415. if (aiNk->settings->isUseFuzzy() && priority < MIN_PRIORITY)
  416. continue;
  417. if (priority <= 0)
  418. continue;
  419. // TODO: Mircea: Move to constant
  420. bool interestingObject = path.turn() <= 2 || priority > (aiNk->settings->isUseFuzzy() ? 0.5f : 0);
  421. if(interestingObject)
  422. {
  423. nearObjects.addObject(obj, path, priority);
  424. }
  425. else
  426. {
  427. farObjects.addObject(obj, path, priority);
  428. }
  429. #if NK2AI_TRACE_LEVEL >= 2
  430. logAi->trace("Path %s added to %s objects. Turn: %d, priority: %f",
  431. path.toString(),
  432. interestingObject ? "near" : "far",
  433. path.turn(),
  434. priority);
  435. #endif
  436. }
  437. }
  438. }