Explore.cpp 10.0 KB

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