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