AIUtility.cpp 14 KB

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