DangerHitMapAnalyzer.cpp 8.8 KB

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