Explore.cpp 9.8 KB

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