DangerHitMapAnalyzer.cpp 8.7 KB

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