DangerHitMapAnalyzer.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 "DangerHitMapAnalyzer.h"
  12. #include "../Engine/Nullkiller.h"
  13. #include "../pforeach.h"
  14. #include "../../../lib/CRandomGenerator.h"
  15. #include "../../../lib/logging/VisualLogger.h"
  16. #include <boost/thread/thread_only.hpp>
  17. namespace NKAI
  18. {
  19. const HitMapInfo HitMapInfo::NoThreat;
  20. double HitMapInfo::value() const
  21. {
  22. return danger / std::sqrt(turn / 3.0f + 1);
  23. }
  24. void logHitmap(PlayerColor playerID, DangerHitMapAnalyzer & data)
  25. {
  26. #if NKAI_TRACE_LEVEL >= 1
  27. logVisual->updateWithLock(playerID.toString() + ".danger.max", [&data](IVisualLogBuilder & b)
  28. {
  29. foreach_tile_pos([&b, &data](const int3 & pos)
  30. {
  31. auto & treat = data.getTileThreat(pos).maximumDanger;
  32. b.addText(pos, std::to_string(treat.danger));
  33. if(treat.hero.validAndSet())
  34. {
  35. b.addText(pos, std::to_string(treat.turn));
  36. b.addText(pos, treat.hero->getNameTranslated());
  37. }
  38. });
  39. });
  40. logVisual->updateWithLock(playerID.toString() + ".danger.fast", [&data](IVisualLogBuilder & b)
  41. {
  42. foreach_tile_pos([&b, &data](const int3 & pos)
  43. {
  44. auto & treat = data.getTileThreat(pos).fastestDanger;
  45. b.addText(pos, std::to_string(treat.danger));
  46. if(treat.hero.validAndSet())
  47. {
  48. b.addText(pos, std::to_string(treat.turn));
  49. b.addText(pos, treat.hero->getNameTranslated());
  50. }
  51. });
  52. });
  53. #endif
  54. }
  55. void DangerHitMapAnalyzer::updateHitMap()
  56. {
  57. if(hitMapUpToDate)
  58. return;
  59. logAi->trace("Update danger hitmap");
  60. hitMapUpToDate = true;
  61. auto start = std::chrono::high_resolution_clock::now();
  62. auto cb = ai->cb.get();
  63. auto mapSize = ai->cb->getMapSize();
  64. if(hitMap.shape()[0] != mapSize.x || hitMap.shape()[1] != mapSize.y || hitMap.shape()[2] != mapSize.z)
  65. hitMap.resize(boost::extents[mapSize.x][mapSize.y][mapSize.z]);
  66. enemyHeroAccessibleObjects.clear();
  67. townThreats.clear();
  68. std::map<PlayerColor, std::map<const CGHeroInstance *, HeroRole>> heroes;
  69. for(const CGObjectInstance * obj : ai->memory->visitableObjs)
  70. {
  71. if(obj->ID == Obj::HERO)
  72. {
  73. auto hero = dynamic_cast<const CGHeroInstance *>(obj);
  74. heroes[hero->tempOwner][hero] = HeroRole::MAIN;
  75. }
  76. if(obj->ID == Obj::TOWN)
  77. {
  78. auto town = dynamic_cast<const CGTownInstance *>(obj);
  79. if(town->garrisonHero)
  80. heroes[town->garrisonHero->tempOwner][town->garrisonHero] = HeroRole::MAIN;
  81. }
  82. }
  83. auto ourTowns = cb->getTownsInfo();
  84. for(auto town : ourTowns)
  85. {
  86. townThreats[town->id]; // insert empty list
  87. }
  88. foreach_tile_pos([&](const int3 & pos){
  89. hitMap[pos.x][pos.y][pos.z].reset();
  90. });
  91. for(auto pair : heroes)
  92. {
  93. if(!pair.first.isValidPlayer())
  94. continue;
  95. if(ai->cb->getPlayerRelations(ai->playerID, pair.first) != PlayerRelations::ENEMIES)
  96. continue;
  97. PathfinderSettings ps;
  98. ps.scoutTurnDistanceLimit = ps.mainTurnDistanceLimit = ai->settings->getThreatTurnDistanceLimit();
  99. ps.useHeroChain = false;
  100. ai->pathfinder->updatePaths(pair.second, ps);
  101. boost::this_thread::interruption_point();
  102. pforeachTilePaths(mapSize, ai, [&](const int3 & pos, const std::vector<AIPath> & paths)
  103. {
  104. for(const AIPath & path : paths)
  105. {
  106. if(path.getFirstBlockedAction())
  107. continue;
  108. auto & node = hitMap[pos.x][pos.y][pos.z];
  109. HitMapInfo newThreat;
  110. newThreat.hero = path.targetHero;
  111. newThreat.turn = path.turn();
  112. newThreat.threat = path.getHeroStrength() * (1 - path.movementCost() / 2.0);
  113. newThreat.danger = path.getHeroStrength();
  114. if(newThreat.value() > node.maximumDanger.value())
  115. {
  116. node.maximumDanger = newThreat;
  117. }
  118. if(newThreat.turn < node.fastestDanger.turn
  119. || (newThreat.turn == node.fastestDanger.turn && node.fastestDanger.danger < newThreat.danger))
  120. {
  121. node.fastestDanger = newThreat;
  122. }
  123. auto objects = cb->getVisitableObjs(pos, false);
  124. for(auto obj : objects)
  125. {
  126. if(obj->ID == Obj::TOWN && obj->getOwner() == ai->playerID)
  127. {
  128. auto & threats = townThreats[obj->id];
  129. auto threat = std::find_if(threats.begin(), threats.end(), [&](const HitMapInfo & i) -> bool
  130. {
  131. return i.hero.hid == path.targetHero->id;
  132. });
  133. if(threat == threats.end())
  134. {
  135. threats.emplace_back();
  136. threat = std::prev(threats.end(), 1);
  137. }
  138. if(newThreat.value() > threat->value())
  139. {
  140. *threat = newThreat;
  141. }
  142. if(newThreat.turn == 0)
  143. {
  144. if(cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES)
  145. enemyHeroAccessibleObjects.emplace_back(path.targetHero, obj);
  146. }
  147. }
  148. }
  149. }
  150. });
  151. }
  152. logAi->trace("Danger hit map updated in %ld", timeElapsed(start));
  153. logHitmap(ai->playerID, *this);
  154. }
  155. void DangerHitMapAnalyzer::calculateTileOwners()
  156. {
  157. if(tileOwnersUpToDate) return;
  158. tileOwnersUpToDate = true;
  159. auto cb = ai->cb.get();
  160. auto mapSize = ai->cb->getMapSize();
  161. if(hitMap.shape()[0] != mapSize.x || hitMap.shape()[1] != mapSize.y || hitMap.shape()[2] != mapSize.z)
  162. hitMap.resize(boost::extents[mapSize.x][mapSize.y][mapSize.z]);
  163. std::vector<std::unique_ptr<CGHeroInstance>> temporaryHeroes;
  164. std::map<const CGHeroInstance *, const CGTownInstance *> heroTownMap;
  165. std::map<const CGHeroInstance *, HeroRole> townHeroes;
  166. auto addTownHero = [&](const CGTownInstance * town)
  167. {
  168. auto townHero = temporaryHeroes.emplace_back(std::make_unique<CGHeroInstance>(town->cb)).get();
  169. CRandomGenerator rng;
  170. auto visitablePos = town->visitablePos();
  171. townHero->setOwner(ai->playerID); // lets avoid having multiple colors
  172. townHero->initHero(rng, static_cast<HeroTypeID>(0));
  173. townHero->pos = townHero->convertFromVisitablePos(visitablePos);
  174. townHero->initObj(rng);
  175. heroTownMap[townHero] = town;
  176. townHeroes[townHero] = HeroRole::MAIN;
  177. };
  178. for(auto obj : ai->memory->visitableObjs)
  179. {
  180. if(obj && obj->ID == Obj::TOWN)
  181. {
  182. addTownHero(dynamic_cast<const CGTownInstance *>(obj));
  183. }
  184. }
  185. for(auto town : cb->getTownsInfo())
  186. {
  187. addTownHero(town);
  188. }
  189. PathfinderSettings ps;
  190. ps.mainTurnDistanceLimit = ps.scoutTurnDistanceLimit = ai->settings->getMainHeroTurnDistanceLimit();
  191. ai->pathfinder->updatePaths(townHeroes, ps);
  192. pforeachTilePaths(mapSize, ai, [&](const int3 & pos, const std::vector<AIPath> & paths)
  193. {
  194. float ourDistance = std::numeric_limits<float>::max();
  195. float enemyDistance = std::numeric_limits<float>::max();
  196. const CGTownInstance * enemyTown = nullptr;
  197. const CGTownInstance * ourTown = nullptr;
  198. for(const AIPath & path : paths)
  199. {
  200. if(!path.targetHero || path.getFirstBlockedAction())
  201. continue;
  202. auto town = heroTownMap[path.targetHero];
  203. if(town->getOwner() == ai->playerID)
  204. {
  205. if(ourDistance > path.movementCost())
  206. {
  207. ourDistance = path.movementCost();
  208. ourTown = town;
  209. }
  210. }
  211. else
  212. {
  213. if(enemyDistance > path.movementCost())
  214. {
  215. enemyDistance = path.movementCost();
  216. enemyTown = town;
  217. }
  218. }
  219. }
  220. if(vstd::isAlmostEqual(ourDistance, enemyDistance))
  221. {
  222. hitMap[pos.x][pos.y][pos.z].closestTown = nullptr;
  223. }
  224. else if(!enemyTown || ourDistance < enemyDistance)
  225. {
  226. hitMap[pos.x][pos.y][pos.z].closestTown = ourTown;
  227. }
  228. else
  229. {
  230. hitMap[pos.x][pos.y][pos.z].closestTown = enemyTown;
  231. }
  232. });
  233. }
  234. const std::vector<HitMapInfo> & DangerHitMapAnalyzer::getTownThreats(const CGTownInstance * town) const
  235. {
  236. static const std::vector<HitMapInfo> empty = {};
  237. auto result = townThreats.find(town->id);
  238. return result == townThreats.end() ? empty : result->second;
  239. }
  240. PlayerColor DangerHitMapAnalyzer::getTileOwner(const int3 & tile) const
  241. {
  242. auto town = hitMap[tile.x][tile.y][tile.z].closestTown;
  243. return town ? town->getOwner() : PlayerColor::NEUTRAL;
  244. }
  245. const CGTownInstance * DangerHitMapAnalyzer::getClosestTown(const int3 & tile) const
  246. {
  247. return hitMap[tile.x][tile.y][tile.z].closestTown;
  248. }
  249. uint64_t DangerHitMapAnalyzer::enemyCanKillOurHeroesAlongThePath(const AIPath & path) const
  250. {
  251. int3 tile = path.targetTile();
  252. int turn = path.turn();
  253. const auto& info = getTileThreat(tile);
  254. return (info.fastestDanger.turn <= turn && !isSafeToVisit(path.targetHero, path.heroArmy, info.fastestDanger.danger, ai->settings->getSafeAttackRatio()))
  255. || (info.maximumDanger.turn <= turn && !isSafeToVisit(path.targetHero, path.heroArmy, info.maximumDanger.danger, ai->settings->getSafeAttackRatio()));
  256. }
  257. const HitMapNode & DangerHitMapAnalyzer::getObjectThreat(const CGObjectInstance * obj) const
  258. {
  259. auto tile = obj->visitablePos();
  260. return getTileThreat(tile);
  261. }
  262. const HitMapNode & DangerHitMapAnalyzer::getTileThreat(const int3 & tile) const
  263. {
  264. return hitMap[tile.x][tile.y][tile.z];
  265. }
  266. std::set<const CGObjectInstance *> DangerHitMapAnalyzer::getOneTurnAccessibleObjects(const CGHeroInstance * enemy) const
  267. {
  268. std::set<const CGObjectInstance *> result;
  269. for(auto & obj : enemyHeroAccessibleObjects)
  270. {
  271. if(obj.hero == enemy)
  272. result.insert(obj.obj);
  273. }
  274. return result;
  275. }
  276. }