DangerHitMapAnalyzer.cpp 8.5 KB

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