DangerHitMapAnalyzer.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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/callback/GameRandomizer.h"
  15. #include "../../../lib/logging/VisualLogger.h"
  16. namespace NK2AI
  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 NK2AI_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 & threat = data.getTileThreat(pos).maximumDanger;
  31. b.addText(pos, std::to_string(threat.danger));
  32. if(threat.heroPtr.isValid())
  33. {
  34. b.addText(pos, std::to_string(threat.turn));
  35. b.addText(pos, threat.heroPtr->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 & threat = data.getTileThreat(pos).fastestDanger;
  44. b.addText(pos, std::to_string(threat.danger));
  45. if(threat.heroPtr.isValid())
  46. {
  47. b.addText(pos, std::to_string(threat.turn));
  48. b.addText(pos, threat.heroPtr->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 cc = aiNk->cc.get();
  62. auto mapSize = aiNk->cc->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 : aiNk->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->getGarrisonHero())
  79. heroes[town->getGarrisonHero()->tempOwner][town->getGarrisonHero()] = HeroRole::MAIN;
  80. }
  81. }
  82. auto ourTowns = cc->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(aiNk->cc->getPlayerRelations(aiNk->playerID, pair.first) != PlayerRelations::ENEMIES)
  95. continue;
  96. PathfinderSettings ps;
  97. ps.scoutTurnDistanceLimit = ps.mainTurnDistanceLimit = aiNk->settings->getThreatTurnDistanceLimit();
  98. ps.useHeroChain = false;
  99. aiNk->pathfinder->updatePaths(pair.second, ps);
  100. aiNk->makingTurnInterrupption.interruptionPoint();
  101. pforeachTilePaths(mapSize, aiNk, [&](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.heroPtr = HeroPtr(path.targetHero);
  110. newThreat.turn = path.turn();
  111. newThreat.threat = path.getHeroStrength() * (1 - path.movementCost() / 2.0);
  112. // TODO: Mircea: Why is this danger calculated so differently than FuzzyHelper::evaluateDanger?
  113. // shouldn't it use the path danger instead of hero strength?
  114. newThreat.danger = path.getHeroStrength();
  115. auto danger2 = aiNk->dangerEvaluator->evaluateDanger(pos, path.targetHero);
  116. logAi->trace("Danger comparison for (%d %d %d) %s is %f vs %f",
  117. pos.x, pos.y, pos.z, path.targetHero->getNameTranslated(), newThreat.danger, danger2);
  118. if(newThreat.value() > node.maximumDanger.value())
  119. {
  120. node.maximumDanger = newThreat;
  121. }
  122. if(newThreat.turn < node.fastestDanger.turn
  123. || (newThreat.turn == node.fastestDanger.turn && node.fastestDanger.danger < newThreat.danger))
  124. {
  125. node.fastestDanger = newThreat;
  126. }
  127. auto objects = cc->getVisitableObjs(pos, false);
  128. for(auto obj : objects)
  129. {
  130. if(obj->ID == Obj::TOWN && obj->getOwner() == aiNk->playerID)
  131. {
  132. auto & threats = townThreats[obj->id];
  133. auto threat = std::find_if(threats.begin(), threats.end(), [&](const HitMapInfo & i) -> bool
  134. {
  135. return i.heroPtr.heroId == path.targetHero->id;
  136. });
  137. if(threat == threats.end())
  138. {
  139. threats.emplace_back();
  140. threat = std::prev(threats.end(), 1);
  141. }
  142. if(newThreat.value() > threat->value())
  143. {
  144. *threat = newThreat;
  145. }
  146. if(newThreat.turn == 0)
  147. {
  148. if(cc->getPlayerRelations(obj->tempOwner, aiNk->playerID) != PlayerRelations::ENEMIES)
  149. enemyHeroAccessibleObjects.emplace_back(path.targetHero, obj);
  150. }
  151. }
  152. }
  153. }
  154. });
  155. }
  156. logAi->trace("Danger hit map updated in %ld", timeElapsed(start));
  157. logHitmap(aiNk->playerID, *this);
  158. }
  159. void DangerHitMapAnalyzer::calculateTileOwners()
  160. {
  161. if(tileOwnersUpToDate) return;
  162. tileOwnersUpToDate = true;
  163. auto * cc = aiNk->cc.get();
  164. auto mapSize = aiNk->cc->getMapSize();
  165. if(hitMap.shape()[0] != mapSize.x || hitMap.shape()[1] != mapSize.y || hitMap.shape()[2] != mapSize.z)
  166. hitMap.resize(boost::extents[mapSize.x][mapSize.y][mapSize.z]);
  167. std::vector<std::unique_ptr<CGHeroInstance>> temporaryHeroes;
  168. std::map<const CGHeroInstance *, const CGTownInstance *> heroTownMap;
  169. std::map<const CGHeroInstance *, HeroRole> townHeroes;
  170. auto addTownHero = [&](const CGTownInstance * town)
  171. {
  172. auto *townHero = temporaryHeroes.emplace_back(std::make_unique<CGHeroInstance>(town->cb)).get();
  173. GameRandomizer randomizer(*town->cb);
  174. auto visitablePos = town->visitablePos();
  175. townHero->id = town->id;
  176. townHero->setOwner(aiNk->playerID); // lets avoid having multiple colors
  177. townHero->initHero(randomizer, static_cast<HeroTypeID>(0));
  178. townHero->pos = townHero->convertFromVisitablePos(visitablePos);
  179. townHero->initObj(randomizer);
  180. heroTownMap[townHero] = town;
  181. townHeroes[townHero] = HeroRole::MAIN;
  182. };
  183. for(const auto *obj : aiNk->memory->visitableObjs)
  184. {
  185. if(obj && obj->ID == Obj::TOWN)
  186. {
  187. addTownHero(dynamic_cast<const CGTownInstance *>(obj));
  188. }
  189. }
  190. for(const auto *town : cc->getTownsInfo())
  191. {
  192. addTownHero(town);
  193. }
  194. PathfinderSettings ps;
  195. ps.mainTurnDistanceLimit = ps.scoutTurnDistanceLimit = aiNk->settings->getMainHeroTurnDistanceLimit();
  196. aiNk->pathfinder->updatePaths(townHeroes, ps);
  197. pforeachTilePaths(mapSize, aiNk, [&](const int3 & pos, const std::vector<AIPath> & paths)
  198. {
  199. float ourDistance = std::numeric_limits<float>::max();
  200. float enemyDistance = std::numeric_limits<float>::max();
  201. const CGTownInstance * enemyTown = nullptr;
  202. const CGTownInstance * ourTown = nullptr;
  203. for(const AIPath & path : paths)
  204. {
  205. if(!path.targetHero || path.getFirstBlockedAction())
  206. continue;
  207. const auto *town = heroTownMap[path.targetHero];
  208. if(town->getOwner() == aiNk->playerID)
  209. {
  210. if(ourDistance > path.movementCost())
  211. {
  212. ourDistance = path.movementCost();
  213. ourTown = town;
  214. }
  215. }
  216. else
  217. {
  218. if(enemyDistance > path.movementCost())
  219. {
  220. enemyDistance = path.movementCost();
  221. enemyTown = town;
  222. }
  223. }
  224. }
  225. if(vstd::isAlmostEqual(ourDistance, enemyDistance))
  226. {
  227. hitMap[pos.x][pos.y][pos.z].closestTown = nullptr;
  228. }
  229. else if(!enemyTown || ourDistance < enemyDistance)
  230. {
  231. hitMap[pos.x][pos.y][pos.z].closestTown = ourTown;
  232. }
  233. else
  234. {
  235. hitMap[pos.x][pos.y][pos.z].closestTown = enemyTown;
  236. }
  237. });
  238. }
  239. const std::vector<HitMapInfo> & DangerHitMapAnalyzer::getTownThreats(const CGTownInstance * town) const
  240. {
  241. static const std::vector<HitMapInfo> empty = {};
  242. auto result = townThreats.find(town->id);
  243. return result == townThreats.end() ? empty : result->second;
  244. }
  245. PlayerColor DangerHitMapAnalyzer::getTileOwner(const int3 & tile) const
  246. {
  247. const auto *town = hitMap[tile.x][tile.y][tile.z].closestTown;
  248. return town ? town->getOwner() : PlayerColor::NEUTRAL;
  249. }
  250. const CGTownInstance * DangerHitMapAnalyzer::getClosestTown(const int3 & tile) const
  251. {
  252. return hitMap[tile.x][tile.y][tile.z].closestTown;
  253. }
  254. uint64_t DangerHitMapAnalyzer::enemyCanKillOurHeroesAlongThePath(const AIPath & path) const
  255. {
  256. int3 tile = path.targetTile();
  257. int turn = path.turn();
  258. const auto& info = getTileThreat(tile);
  259. return (info.fastestDanger.turn <= turn && !isSafeToVisit(path.targetHero, path.heroArmy, info.fastestDanger.danger, aiNk->settings->getSafeAttackRatio()))
  260. || (info.maximumDanger.turn <= turn && !isSafeToVisit(path.targetHero, path.heroArmy, info.maximumDanger.danger, aiNk->settings->getSafeAttackRatio()));
  261. }
  262. const HitMapNode & DangerHitMapAnalyzer::getObjectThreat(const CGObjectInstance * obj) const
  263. {
  264. auto tile = obj->visitablePos();
  265. return getTileThreat(tile);
  266. }
  267. const HitMapNode & DangerHitMapAnalyzer::getTileThreat(const int3 & tile) const
  268. {
  269. return hitMap[tile.x][tile.y][tile.z];
  270. }
  271. std::set<const CGObjectInstance *> DangerHitMapAnalyzer::getOneTurnAccessibleObjects(const CGHeroInstance * enemy) const
  272. {
  273. std::set<const CGObjectInstance *> result;
  274. for(const auto & obj : enemyHeroAccessibleObjects)
  275. {
  276. if(obj.hero == enemy)
  277. result.insert(obj.obj);
  278. }
  279. return result;
  280. }
  281. }