Explore.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /*
  2. * Explore.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 "Goals.h"
  12. #include "../VCAI.h"
  13. #include "../AIUtility.h"
  14. #include "../AIhelper.h"
  15. #include "../FuzzyHelper.h"
  16. #include "../ResourceManager.h"
  17. #include "../BuildingManager.h"
  18. #include "../../../lib/mapping/CMap.h" //for victory conditions
  19. #include "../../../lib/CPathfinder.h"
  20. #include "../../../lib/StringConstants.h"
  21. #include "../../../lib/CPlayerState.h"
  22. extern boost::thread_specific_ptr<CCallback> cb;
  23. extern boost::thread_specific_ptr<VCAI> ai;
  24. extern FuzzyHelper * fh;
  25. using namespace Goals;
  26. bool Explore::operator==(const Explore & other) const
  27. {
  28. return other.hero.h == hero.h && other.allowGatherArmy == allowGatherArmy;
  29. }
  30. std::string Explore::completeMessage() const
  31. {
  32. return "Hero " + hero.get()->name + " completed exploration";
  33. }
  34. TSubgoal Explore::whatToDoToAchieve()
  35. {
  36. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  37. if(hero) //use best step for this hero
  38. {
  39. return ret;
  40. }
  41. else
  42. {
  43. if(ret->hero.get(true))
  44. return sptr(Explore().sethero(ret->hero.h)); //choose this hero and then continue with him
  45. else
  46. return ret; //other solutions, like buying hero from tavern
  47. }
  48. }
  49. TGoalVec Explore::getAllPossibleSubgoals()
  50. {
  51. TGoalVec ret;
  52. std::vector<const CGHeroInstance *> heroes;
  53. if(hero)
  54. {
  55. heroes.push_back(hero.h);
  56. }
  57. else
  58. {
  59. //heroes = ai->getUnblockedHeroes();
  60. heroes = cb->getHeroesInfo();
  61. vstd::erase_if(heroes, [](const HeroPtr h)
  62. {
  63. if(ai->getGoal(h)->goalType == EXPLORE) //do not reassign hero who is already explorer
  64. return true;
  65. if(!ai->isAbleToExplore(h))
  66. return true;
  67. return !h->movement; //saves time, immobile heroes are useless anyway
  68. });
  69. }
  70. //try to use buildings that uncover map
  71. std::vector<const CGObjectInstance *> objs;
  72. for(auto obj : ai->visitableObjs)
  73. {
  74. if(!vstd::contains(ai->alreadyVisited, obj))
  75. {
  76. switch(obj->ID.num)
  77. {
  78. case Obj::REDWOOD_OBSERVATORY:
  79. case Obj::PILLAR_OF_FIRE:
  80. case Obj::CARTOGRAPHER:
  81. objs.push_back(obj);
  82. break;
  83. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  84. case Obj::MONOLITH_TWO_WAY:
  85. case Obj::SUBTERRANEAN_GATE:
  86. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  87. assert(ai->knownTeleportChannels.find(tObj->channel) != ai->knownTeleportChannels.end());
  88. if(TeleportChannel::IMPASSABLE != ai->knownTeleportChannels[tObj->channel]->passability)
  89. objs.push_back(obj);
  90. break;
  91. }
  92. }
  93. else
  94. {
  95. switch(obj->ID.num)
  96. {
  97. case Obj::MONOLITH_TWO_WAY:
  98. case Obj::SUBTERRANEAN_GATE:
  99. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  100. if(TeleportChannel::IMPASSABLE == ai->knownTeleportChannels[tObj->channel]->passability)
  101. break;
  102. for(auto exit : ai->knownTeleportChannels[tObj->channel]->exits)
  103. {
  104. if(!cb->getObj(exit))
  105. { // Always attempt to visit two-way teleports if one of channel exits is not visible
  106. objs.push_back(obj);
  107. break;
  108. }
  109. }
  110. break;
  111. }
  112. }
  113. }
  114. for(auto h : heroes)
  115. {
  116. for(auto obj : objs) //double loop, performance risk?
  117. {
  118. auto waysToVisitObj = ai->ah->howToVisitObj(h, obj, allowGatherArmy);
  119. vstd::concatenate(ret, waysToVisitObj);
  120. }
  121. TSubgoal goal = exploreNearestNeighbour(h);
  122. if(!goal->invalid())
  123. {
  124. ret.push_back(goal);
  125. }
  126. }
  127. if(ret.empty())
  128. {
  129. for(auto h : heroes)
  130. {
  131. TSubgoal goal = explorationNewPoint(h);
  132. if(goal->invalid())
  133. {
  134. ai->markHeroUnableToExplore(h); //there is no freely accessible tile, do not poll this hero anymore
  135. }
  136. else
  137. {
  138. ret.push_back(goal);
  139. }
  140. }
  141. }
  142. //we either don't have hero yet or none of heroes can explore
  143. if((!hero || ret.empty()) && ai->canRecruitAnyHero())
  144. ret.push_back(sptr(RecruitHero()));
  145. if(ret.empty())
  146. {
  147. throw goalFulfilledException(sptr(Explore().sethero(hero)));
  148. }
  149. return ret;
  150. }
  151. bool Explore::fulfillsMe(TSubgoal goal)
  152. {
  153. if(goal->goalType == EXPLORE)
  154. {
  155. if(goal->hero)
  156. return hero == goal->hero;
  157. else
  158. return true; //cancel ALL exploration
  159. }
  160. return false;
  161. }
  162. bool Explore::hasReachableNeighbor(const int3 &pos, HeroPtr hero, CCallback * cbp, VCAI * vcai) const
  163. {
  164. for(crint3 dir : int3::getDirs())
  165. {
  166. int3 tile = pos + dir;
  167. if(cbp->isInTheMap(tile))
  168. {
  169. auto isAccessible = vcai->ah->isTileAccessible(hero, tile);
  170. if(isAccessible)
  171. return true;
  172. }
  173. }
  174. return false;
  175. }
  176. int Explore::howManyTilesWillBeDiscovered(
  177. const int3 & pos,
  178. int radious,
  179. CCallback * cbp,
  180. const TeamState * ts,
  181. VCAI * aip,
  182. HeroPtr h) const
  183. {
  184. int ret = 0;
  185. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  186. {
  187. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  188. {
  189. int3 npos = int3(x, y, pos.z);
  190. if(cbp->isInTheMap(npos)
  191. && pos.dist2d(npos) - 0.5 < radious
  192. && !ts->fogOfWarMap[npos.x][npos.y][npos.z]
  193. && hasReachableNeighbor(npos, h, cbp, aip))
  194. {
  195. ret++;
  196. }
  197. }
  198. }
  199. return ret;
  200. }
  201. TSubgoal Explore::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h) const
  202. {
  203. std::map<int3, int> dstToRevealedTiles;
  204. VCAI * aip = ai.get();
  205. CCallback * cbp = cb.get();
  206. const TeamState * ts = cbp->getPlayerTeam(ai->playerID);
  207. for(crint3 dir : int3::getDirs())
  208. {
  209. int3 tile = hpos + dir;
  210. if(cb->isInTheMap(tile))
  211. {
  212. if(isBlockVisitObj(tile))
  213. continue;
  214. if(isSafeToVisit(h, tile) && ai->isAccessibleForHero(tile, h))
  215. {
  216. auto distance = hpos.dist2d(tile); // diagonal movement opens more tiles but spends more mp
  217. int tilesDiscovered = howManyTilesWillBeDiscovered(tile, radius, cbp, ts, aip, h);
  218. if(tilesDiscovered > 0)
  219. dstToRevealedTiles[tile] = tilesDiscovered / distance;
  220. }
  221. }
  222. }
  223. if(dstToRevealedTiles.empty()) //yes, it DID happen!
  224. return sptr(Invalid());
  225. auto best = dstToRevealedTiles.begin();
  226. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  227. {
  228. const CGPathNode * pn = cb->getPathsInfo(h.get())->getPathInfo(i->first);
  229. //const TerrainTile *t = cb->getTile(i->first);
  230. if(best->second < i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  231. best = i;
  232. }
  233. if(best->second)
  234. return sptr(VisitTile(best->first).sethero(h));
  235. return sptr(Invalid());
  236. }
  237. TSubgoal Explore::explorationNewPoint(HeroPtr h) const
  238. {
  239. int radius = h->getSightRadius();
  240. CCallback * cbp = cb.get();
  241. VCAI *aip = ai.get();
  242. const TeamState * ts = cbp->getPlayerTeam(aip->playerID);
  243. int3 mapSize = cbp->getMapSize();
  244. int perimiter = 2 * radius * (mapSize.x + mapSize.y);
  245. std::vector<int3> from;
  246. std::vector<int3> to;
  247. from.reserve(perimiter);
  248. to.reserve(perimiter);
  249. foreach_tile_pos([&](const int3 & pos)
  250. {
  251. if(ts->fogOfWarMap[pos.x][pos.y][pos.z])
  252. {
  253. bool hasInvisibleNeighbor = false;
  254. foreach_neighbour(cbp, pos, [&](CCallback * cbp, int3 neighbour)
  255. {
  256. if(!ts->fogOfWarMap[neighbour.x][neighbour.y][neighbour.z])
  257. {
  258. hasInvisibleNeighbor = true;
  259. }
  260. });
  261. if(hasInvisibleNeighbor)
  262. from.push_back(pos);
  263. }
  264. });
  265. for(int i = 0; i < radius; i++)
  266. {
  267. getVisibleNeighbours(from, to, cbp, ts);
  268. vstd::concatenate(from, to);
  269. vstd::removeDuplicates(from);
  270. }
  271. return explorationScanRange(h, from);
  272. }
  273. TSubgoal Explore::explorationScanRange(HeroPtr h, std::vector<int3> & range) const
  274. {
  275. int radius = h->getSightRadius();
  276. CCallback * cbp = cb.get();
  277. VCAI *aip = ai.get();
  278. const TeamState * ts = cbp->getPlayerTeam(aip->playerID);
  279. float bestValue = 0; //discovered tile to node distance ratio
  280. TSubgoal bestWay = sptr(Invalid());
  281. int3 ourPos = h->convertPosition(h->pos, false);
  282. for(const int3 & tile : range)
  283. {
  284. if(tile == ourPos) //shouldn't happen, but it does
  285. continue;
  286. int tilesDiscovered = howManyTilesWillBeDiscovered(tile, radius, cbp, ts, aip, h);
  287. if(!tilesDiscovered)
  288. continue;
  289. auto waysToVisit = aip->ah->howToVisitTile(h, tile, allowGatherArmy);
  290. for(auto goal : waysToVisit)
  291. {
  292. if(goal->evaluationContext.movementCost == 0) // should not happen
  293. continue;
  294. float ourValue = (float)tilesDiscovered * tilesDiscovered / goal->evaluationContext.movementCost;
  295. if(ourValue > bestValue) //avoid costly checks of tiles that don't reveal much
  296. {
  297. auto obj = cb->getTopObj(tile);
  298. if(obj && obj->blockVisit && !isObjectRemovable(obj)) //we can't stand on that object
  299. {
  300. continue;
  301. }
  302. if(isSafeToVisit(h, tile))
  303. {
  304. bestWay = goal;
  305. bestValue = ourValue;
  306. }
  307. }
  308. }
  309. }
  310. if(!bestWay->invalid())
  311. {
  312. return bestWay;
  313. }
  314. return bestWay;
  315. }
  316. TSubgoal Explore::exploreNearestNeighbour(HeroPtr h) const
  317. {
  318. TimeCheck tc("where to explore");
  319. int radius = h->getSightRadius();
  320. int3 hpos = h->visitablePos();
  321. //look for nearby objs -> visit them if they're close enough
  322. const int DIST_LIMIT = 3;
  323. const int MP_LIMIT = DIST_LIMIT * 150; // approximate cost of diagonal movement
  324. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  325. for(int x = hpos.x - DIST_LIMIT; x <= hpos.x + DIST_LIMIT; ++x) //get only local objects instead of all possible objects on the map
  326. {
  327. for(int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
  328. {
  329. for(auto obj : cb->getVisitableObjs(int3(x, y, hpos.z), false))
  330. {
  331. if(ai->isGoodForVisit(obj, h, MP_LIMIT))
  332. {
  333. nearbyVisitableObjs.push_back(obj);
  334. }
  335. }
  336. }
  337. }
  338. if(nearbyVisitableObjs.size())
  339. {
  340. vstd::removeDuplicates(nearbyVisitableObjs); //one object may occupy multiple tiles
  341. boost::sort(nearbyVisitableObjs, CDistanceSorter(h.get()));
  342. TSubgoal pickupNearestObj = fh->chooseSolution(ai->ah->howToVisitObj(h, nearbyVisitableObjs.back(), false));
  343. if(!pickupNearestObj->invalid())
  344. {
  345. return pickupNearestObj;
  346. }
  347. }
  348. //check if nearby tiles allow us to reveal anything - this is quick
  349. return explorationBestNeighbour(hpos, radius, h);
  350. }
  351. void Explore::getVisibleNeighbours(const std::vector<int3> & tiles, std::vector<int3> & out, CCallback * cbp, const TeamState * ts) const
  352. {
  353. for(const int3 & tile : tiles)
  354. {
  355. foreach_neighbour(cbp, tile, [&](CCallback * cbp, int3 neighbour)
  356. {
  357. if(ts->fogOfWarMap[neighbour.x][neighbour.y][neighbour.z])
  358. {
  359. out.push_back(neighbour);
  360. }
  361. });
  362. }
  363. }