AIUtility.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. #include "StdInc.h"
  2. #include "AIUtility.h"
  3. #include "VCAI.h"
  4. #include "../../lib/UnlockGuard.h"
  5. #include "../../lib/CObjectHandler.h"
  6. #include "../../lib/CConfigHandler.h"
  7. #include "../../lib/CHeroHandler.h"
  8. /*
  9. * AIUtility.cpp, part of VCMI engine
  10. *
  11. * Authors: listed in file AUTHORS in main folder
  12. *
  13. * License: GNU General Public License v2.0 or later
  14. * Full text of license available in license.txt file, in main folder
  15. *
  16. */
  17. extern boost::thread_specific_ptr<CCallback> cb;
  18. extern boost::thread_specific_ptr<VCAI> ai;
  19. extern FuzzyHelper *fh;
  20. //extern static const int3 dirs[8];
  21. const CGObjectInstance * ObjectIdRef::operator->() const
  22. {
  23. return cb->getObj(id, false);
  24. }
  25. ObjectIdRef::operator const CGObjectInstance*() const
  26. {
  27. return cb->getObj(id, false);
  28. }
  29. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id) : id(_id)
  30. {
  31. }
  32. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  33. {
  34. }
  35. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  36. {
  37. return id < rhs.id;
  38. }
  39. HeroPtr::HeroPtr(const CGHeroInstance *H)
  40. {
  41. if(!H)
  42. {
  43. //init from nullptr should equal to default init
  44. *this = HeroPtr();
  45. return;
  46. }
  47. h = H;
  48. name = h->name;
  49. hid = H->id;
  50. // infosCount[ai->playerID][hid]++;
  51. }
  52. HeroPtr::HeroPtr()
  53. {
  54. h = nullptr;
  55. hid = ObjectInstanceID();
  56. }
  57. HeroPtr::~HeroPtr()
  58. {
  59. // if(hid >= 0)
  60. // infosCount[ai->playerID][hid]--;
  61. }
  62. bool HeroPtr::operator<(const HeroPtr &rhs) const
  63. {
  64. return hid < rhs.hid;
  65. }
  66. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
  67. {
  68. //TODO? check if these all assertions every time we get info about hero affect efficiency
  69. //
  70. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  71. assert(doWeExpectNull || h);
  72. if(h)
  73. {
  74. auto obj = cb->getObj(hid);
  75. const bool owned = obj && obj->tempOwner == ai->playerID;
  76. if(doWeExpectNull && !owned)
  77. {
  78. return nullptr;
  79. }
  80. else
  81. {
  82. assert(obj);
  83. assert(owned);
  84. }
  85. }
  86. return h;
  87. }
  88. const CGHeroInstance * HeroPtr::operator->() const
  89. {
  90. return get();
  91. }
  92. bool HeroPtr::validAndSet() const
  93. {
  94. return get(true);
  95. }
  96. const CGHeroInstance * HeroPtr::operator*() const
  97. {
  98. return get();
  99. }
  100. void foreach_tile_pos(std::function<void(const int3& pos)> foo)
  101. {
  102. for(int i = 0; i < cb->getMapSize().x; i++)
  103. for(int j = 0; j < cb->getMapSize().y; j++)
  104. for(int k = 0; k < cb->getMapSize().z; k++)
  105. foo(int3(i,j,k));
  106. }
  107. void foreach_neighbour(const int3 &pos, std::function<void(const int3& pos)> foo)
  108. {
  109. for(const int3 &dir : dirs)
  110. {
  111. const int3 n = pos + dir;
  112. if(cb->isInTheMap(n))
  113. foo(pos+dir);
  114. }
  115. }
  116. std::string strFromInt3(int3 pos)
  117. {
  118. std::ostringstream oss;
  119. oss << pos;
  120. return oss.str();
  121. }
  122. bool isCloser(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  123. {
  124. const CGPathNode *ln = cb->getPathInfo(lhs->visitablePos()), *rn = cb->getPathInfo(rhs->visitablePos());
  125. if(ln->turns != rn->turns)
  126. return ln->turns < rn->turns;
  127. return (ln->moveRemains > rn->moveRemains);
  128. }
  129. bool compareMovement(HeroPtr lhs, HeroPtr rhs)
  130. {
  131. return lhs->movement > rhs->movement;
  132. }
  133. ui64 evaluateDanger(crint3 tile)
  134. {
  135. const TerrainTile *t = cb->getTile(tile, false);
  136. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  137. return 190000000; //MUCH
  138. ui64 objectDanger = 0, guardDanger = 0;
  139. auto visObjs = cb->getVisitableObjs(tile);
  140. if(visObjs.size())
  141. objectDanger = evaluateDanger(visObjs.back());
  142. int3 guardPos = cb->guardingCreaturePosition(tile);
  143. if(guardPos.x >= 0 && guardPos != tile)
  144. guardDanger = evaluateDanger(guardPos);
  145. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  146. return std::max(objectDanger, guardDanger);
  147. }
  148. ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
  149. {
  150. const TerrainTile *t = cb->getTile(tile, false);
  151. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  152. return 190000000; //MUCH
  153. ui64 objectDanger = 0, guardDanger = 0;
  154. auto visitableObjects = cb->getVisitableObjs(tile);
  155. // in some scenarios hero happens to be "under" the object (eg town). Then we consider ONLY the hero.
  156. if(vstd::contains_if(visitableObjects, objWithID<Obj::HERO>))
  157. vstd::erase_if(visitableObjects, [](const CGObjectInstance * obj)
  158. {
  159. return !objWithID<Obj::HERO>(obj);
  160. });
  161. if(const CGObjectInstance * dangerousObject = vstd::backOrNull(visitableObjects))
  162. {
  163. objectDanger = evaluateDanger(dangerousObject); //unguarded objects can also be dangerous or unhandled
  164. if (objectDanger)
  165. {
  166. //TODO: don't downcast objects AI shouldn't know about!
  167. auto armedObj = dynamic_cast<const CArmedInstance*>(dangerousObject);
  168. if(armedObj)
  169. objectDanger *= fh->getTacticalAdvantage(visitor, armedObj); //this line tends to go infinite for allied towns (?)
  170. }
  171. if (dangerousObject->ID == Obj::SUBTERRANEAN_GATE)
  172. { //check guard on the other side of the gate
  173. auto it = ai->knownSubterraneanGates.find(dangerousObject);
  174. if (it != ai->knownSubterraneanGates.end())
  175. {
  176. auto guards = cb->getGuardingCreatures(it->second->visitablePos());
  177. for (auto cre : guards)
  178. {
  179. vstd::amax (guardDanger, evaluateDanger(cre) *
  180. fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre)));
  181. }
  182. }
  183. }
  184. }
  185. auto guards = cb->getGuardingCreatures(tile);
  186. for (auto cre : guards)
  187. {
  188. vstd::amax (guardDanger, evaluateDanger(cre) * fh->getTacticalAdvantage(visitor, dynamic_cast<const CArmedInstance*>(cre))); //we are interested in strongest monster around
  189. }
  190. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  191. return std::max(objectDanger, guardDanger);
  192. }
  193. ui64 evaluateDanger(const CGObjectInstance *obj)
  194. {
  195. if(obj->tempOwner < PlayerColor::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID) != PlayerRelations::ENEMIES) //owned or allied objects don't pose any threat
  196. return 0;
  197. switch(obj->ID)
  198. {
  199. case Obj::HERO:
  200. {
  201. InfoAboutHero iah;
  202. cb->getHeroInfo(obj, iah);
  203. return iah.army.getStrength();
  204. }
  205. case Obj::TOWN:
  206. case Obj::GARRISON: case Obj::GARRISON2: //garrison
  207. {
  208. InfoAboutTown iat;
  209. cb->getTownInfo(obj, iat);
  210. return iat.army.getStrength();
  211. }
  212. case Obj::MONSTER:
  213. {
  214. //TODO!!!!!!!!
  215. const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
  216. return cre->getArmyStrength();
  217. }
  218. case Obj::CREATURE_GENERATOR1:
  219. {
  220. const CGDwelling *d = dynamic_cast<const CGDwelling*>(obj);
  221. return d->getArmyStrength();
  222. }
  223. case Obj::MINE:
  224. case Obj::ABANDONED_MINE:
  225. {
  226. const CArmedInstance * a = dynamic_cast<const CArmedInstance*>(obj);
  227. return a->getArmyStrength();
  228. }
  229. case Obj::CRYPT: //crypt
  230. case Obj::CREATURE_BANK: //crebank
  231. case Obj::DRAGON_UTOPIA:
  232. case Obj::SHIPWRECK: //shipwreck
  233. case Obj::DERELICT_SHIP: //derelict ship
  234. // case Obj::PYRAMID:
  235. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  236. case Obj::PYRAMID:
  237. {
  238. if(obj->subID == 0)
  239. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  240. else
  241. return 0;
  242. }
  243. default:
  244. return 0;
  245. }
  246. }
  247. bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  248. {
  249. return evaluateDanger(lhs) < evaluateDanger(rhs);
  250. }
  251. bool isSafeToVisit(HeroPtr h, crint3 tile)
  252. {
  253. const ui64 heroStrength = h->getTotalStrength(),
  254. dangerStrength = evaluateDanger(tile, *h);
  255. if(dangerStrength)
  256. {
  257. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  258. {
  259. logAi->traceStream() << boost::format("It's safe for %s to visit tile %s") % h->name % tile;
  260. return true;
  261. }
  262. else
  263. return false;
  264. }
  265. return true; //there's no danger
  266. }
  267. bool isReachable(const CGObjectInstance *obj)
  268. {
  269. return cb->getPathInfo(obj->visitablePos())->turns < 255;
  270. }
  271. bool canBeEmbarkmentPoint(const TerrainTile *t)
  272. {
  273. //tile must be free of with unoccupied boat
  274. return !t->blocked
  275. || (t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT);
  276. }
  277. int3 whereToExplore(HeroPtr h)
  278. {
  279. TimeCheck tc ("where to explore");
  280. cb->setSelection(*h);
  281. int radius = h->getSightRadious();
  282. int3 hpos = h->visitablePos();
  283. //look for nearby objs -> visit them if they're close enouh
  284. const int DIST_LIMIT = 3;
  285. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  286. 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
  287. {
  288. for (int y = hpos.y - DIST_LIMIT; y <= hpos.y + DIST_LIMIT; ++y)
  289. {
  290. for (auto obj : cb->getVisitableObjs (int3(x,y,hpos.z), false))
  291. {
  292. int3 op = obj->visitablePos();
  293. CGPath p;
  294. cb->getPath2(op, p);
  295. if (p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  296. if (ai->isGoodForVisit(obj, h))
  297. nearbyVisitableObjs.push_back(obj);
  298. }
  299. }
  300. }
  301. removeDuplicates (nearbyVisitableObjs); //one object may occupy multiple tiles
  302. boost::sort(nearbyVisitableObjs, isCloser);
  303. if(nearbyVisitableObjs.size())
  304. return nearbyVisitableObjs.back()->visitablePos();
  305. try //check if nearby tiles allow us to reveal anything - this is quick
  306. {
  307. return ai->explorationBestNeighbour(hpos, radius, h);
  308. }
  309. catch(cannotFulfillGoalException &e)
  310. {
  311. //perform exhaustive search
  312. return ai->explorationNewPoint(h);
  313. }
  314. }
  315. bool isBlockedBorderGate(int3 tileToHit)
  316. {
  317. return cb->getTile(tileToHit)->topVisitableId() == Obj::BORDER_GATE
  318. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  319. }
  320. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  321. { //TODO: do not explore dead-end boundaries
  322. int ret = 0;
  323. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  324. {
  325. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  326. {
  327. int3 npos = int3(x,y,pos.z);
  328. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  329. {
  330. if (!boundaryBetweenTwoPoints (pos, npos))
  331. ret++;
  332. }
  333. }
  334. }
  335. return ret;
  336. }
  337. bool boundaryBetweenTwoPoints (int3 pos1, int3 pos2) //determines if two points are separated by known barrier
  338. {
  339. int xMin = std::min (pos1.x, pos2.x);
  340. int xMax = std::max (pos1.x, pos2.x);
  341. int yMin = std::min (pos1.y, pos2.y);
  342. int yMax = std::max (pos1.y, pos2.y);
  343. for (int x = xMin; x <= xMax; ++x)
  344. {
  345. for (int y = yMin; y <= yMax; ++y)
  346. {
  347. int3 tile = int3(x, y, pos1.z); //use only on same level, ofc
  348. if (abs(pos1.dist2d(tile) - pos2.dist2d(tile)) < 1.5)
  349. {
  350. if (!(cb->isVisible(tile) && cb->getTile(tile)->blocked)) //if there's invisible or unblocked tile between, it's good
  351. return false;
  352. }
  353. }
  354. }
  355. return true; //if all are visible and blocked, we're at dead end
  356. }
  357. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  358. {
  359. return howManyTilesWillBeDiscovered(pos + dir, radious);
  360. }
  361. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  362. {
  363. for(const int3 &tile : tiles)
  364. {
  365. foreach_neighbour(tile, [&](int3 neighbour)
  366. {
  367. if(cb->isVisible(neighbour))
  368. out.push_back(neighbour);
  369. });
  370. }
  371. }
  372. ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t)
  373. {
  374. ui64 ret = 0;
  375. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  376. std::vector<const CStackInstance *> toMove;
  377. for(auto const slot : t->Slots())
  378. {
  379. //can be merged woth another stack?
  380. SlotID dst = h->getSlotFor(slot.second->getCreatureID());
  381. if(h->hasStackAtSlot(dst))
  382. ret += t->getPower(slot.first);
  383. else
  384. toMove.push_back(slot.second);
  385. }
  386. boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
  387. {
  388. return lhs->getPower() < rhs->getPower();
  389. });
  390. for (auto & stack : boost::adaptors::reverse(toMove))
  391. {
  392. if(freeHeroSlots)
  393. {
  394. ret += stack->getPower();
  395. freeHeroSlots--;
  396. }
  397. else
  398. break;
  399. }
  400. return ret;
  401. }
  402. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  403. {
  404. return h1->getTotalStrength() < h2->getTotalStrength();
  405. }
  406. bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
  407. {
  408. return a1->getArmyStrength() < a2->getArmyStrength();
  409. }