AIUtility.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 "AIGateway.h"
  13. #include "Goals/Goals.h"
  14. #include "../../lib/UnlockGuard.h"
  15. #include "../../lib/CConfigHandler.h"
  16. #include "../../lib/CHeroHandler.h"
  17. #include "../../lib/mapObjects/MapObjects.h"
  18. #include "../../lib/mapping/CMapDefines.h"
  19. #include "../../lib/gameState/QuestInfo.h"
  20. #include "../../lib/GameSettings.h"
  21. #include <vcmi/CreatureService.h>
  22. namespace NKAI
  23. {
  24. const CGObjectInstance * ObjectIdRef::operator->() const
  25. {
  26. return cb->getObj(id, false);
  27. }
  28. ObjectIdRef::operator const CGObjectInstance *() const
  29. {
  30. return cb->getObj(id, false);
  31. }
  32. ObjectIdRef::operator bool() const
  33. {
  34. return cb->getObj(id, false);
  35. }
  36. ObjectIdRef::ObjectIdRef(ObjectInstanceID _id)
  37. : id(_id)
  38. {
  39. }
  40. ObjectIdRef::ObjectIdRef(const CGObjectInstance * obj)
  41. : id(obj->id)
  42. {
  43. }
  44. bool ObjectIdRef::operator<(const ObjectIdRef & rhs) const
  45. {
  46. return id < rhs.id;
  47. }
  48. HeroPtr::HeroPtr(const CGHeroInstance * H)
  49. {
  50. if(!H)
  51. {
  52. //init from nullptr should equal to default init
  53. *this = HeroPtr();
  54. return;
  55. }
  56. h = H;
  57. name = h->getNameTranslated();
  58. hid = H->id;
  59. // infosCount[ai->playerID][hid]++;
  60. }
  61. HeroPtr::HeroPtr()
  62. {
  63. h = nullptr;
  64. hid = ObjectInstanceID();
  65. }
  66. HeroPtr::~HeroPtr()
  67. {
  68. // if(hid >= 0)
  69. // infosCount[ai->playerID][hid]--;
  70. }
  71. bool HeroPtr::operator<(const HeroPtr & rhs) const
  72. {
  73. return hid < rhs.hid;
  74. }
  75. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull) const
  76. {
  77. //TODO? check if these all assertions every time we get info about hero affect efficiency
  78. //
  79. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  80. assert(doWeExpectNull || h);
  81. if(h)
  82. {
  83. auto obj = cb->getObj(hid);
  84. //const bool owned = obj && obj->tempOwner == ai->playerID;
  85. if(doWeExpectNull && !obj)
  86. {
  87. return nullptr;
  88. }
  89. else
  90. {
  91. if (!obj)
  92. logAi->error("Accessing no longer accessible hero %s!", h->getNameTranslated());
  93. //assert(obj);
  94. //assert(owned);
  95. }
  96. }
  97. return h;
  98. }
  99. const CGHeroInstance * HeroPtr::get(CCallback * cb, bool doWeExpectNull) const
  100. {
  101. //TODO? check if these all assertions every time we get info about hero affect efficiency
  102. //
  103. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  104. assert(doWeExpectNull || h);
  105. if(h)
  106. {
  107. auto obj = cb->getObj(hid);
  108. //const bool owned = obj && obj->tempOwner == ai->playerID;
  109. if(doWeExpectNull && !obj)
  110. {
  111. return nullptr;
  112. }
  113. else
  114. {
  115. assert(obj);
  116. //assert(owned);
  117. }
  118. }
  119. return h;
  120. }
  121. const CGHeroInstance * HeroPtr::operator->() const
  122. {
  123. return get();
  124. }
  125. bool HeroPtr::validAndSet() const
  126. {
  127. return get(true);
  128. }
  129. const CGHeroInstance * HeroPtr::operator*() const
  130. {
  131. return get();
  132. }
  133. bool HeroPtr::operator==(const HeroPtr & rhs) const
  134. {
  135. return h == rhs.get(true);
  136. }
  137. bool CDistanceSorter::operator()(const CGObjectInstance * lhs, const CGObjectInstance * rhs) const
  138. {
  139. const CGPathNode * ln = ai->myCb->getPathsInfo(hero)->getPathInfo(lhs->visitablePos());
  140. const CGPathNode * rn = ai->myCb->getPathsInfo(hero)->getPathInfo(rhs->visitablePos());
  141. return ln->getCost() < rn->getCost();
  142. }
  143. bool isSafeToVisit(HeroPtr h, const CCreatureSet * heroArmy, uint64_t dangerStrength)
  144. {
  145. const ui64 heroStrength = h->getFightingStrength() * heroArmy->getArmyStrength();
  146. if(dangerStrength)
  147. {
  148. return heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength;
  149. }
  150. return true; //there's no danger
  151. }
  152. bool isSafeToVisit(HeroPtr h, uint64_t dangerStrength)
  153. {
  154. return isSafeToVisit(h, h.get(), dangerStrength);
  155. }
  156. bool isObjectRemovable(const CGObjectInstance * obj)
  157. {
  158. //FIXME: move logic to object property!
  159. switch (obj->ID)
  160. {
  161. case Obj::MONSTER:
  162. case Obj::RESOURCE:
  163. case Obj::CAMPFIRE:
  164. case Obj::TREASURE_CHEST:
  165. case Obj::ARTIFACT:
  166. case Obj::BORDERGUARD:
  167. case Obj::FLOTSAM:
  168. case Obj::PANDORAS_BOX:
  169. case Obj::OCEAN_BOTTLE:
  170. case Obj::SEA_CHEST:
  171. case Obj::SHIPWRECK_SURVIVOR:
  172. case Obj::SPELL_SCROLL:
  173. return true;
  174. break;
  175. default:
  176. return false;
  177. break;
  178. }
  179. }
  180. bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater)
  181. {
  182. // TODO: Such information should be provided by pathfinder
  183. // Tile must be free or with unoccupied boat
  184. if(!t->blocked)
  185. {
  186. return true;
  187. }
  188. else if(!fromWater) // do not try to board when in water sector
  189. {
  190. if(t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT)
  191. return true;
  192. }
  193. return false;
  194. }
  195. bool isObjectPassable(const Nullkiller * ai, const CGObjectInstance * obj)
  196. {
  197. return isObjectPassable(obj, ai->playerID, ai->cb->getPlayerRelations(obj->tempOwner, ai->playerID));
  198. }
  199. bool isObjectPassable(const CGObjectInstance * obj)
  200. {
  201. return isObjectPassable(obj, ai->playerID, ai->myCb->getPlayerRelations(obj->tempOwner, ai->playerID));
  202. }
  203. // Pathfinder internal helper
  204. bool isObjectPassable(const CGObjectInstance * obj, PlayerColor playerColor, PlayerRelations objectRelations)
  205. {
  206. if((obj->ID == Obj::GARRISON || obj->ID == Obj::GARRISON2)
  207. && objectRelations != PlayerRelations::ENEMIES)
  208. return true;
  209. if(obj->ID == Obj::BORDER_GATE)
  210. {
  211. auto quest = dynamic_cast<const CGKeys *>(obj);
  212. if(quest->wasMyColorVisited(playerColor))
  213. return true;
  214. }
  215. return false;
  216. }
  217. bool isBlockVisitObj(const int3 & pos)
  218. {
  219. if(auto obj = cb->getTopObj(pos))
  220. {
  221. if(obj->isBlockedVisitable()) //we can't stand on that object
  222. return true;
  223. }
  224. return false;
  225. }
  226. creInfo infoFromDC(const dwellingContent & dc)
  227. {
  228. creInfo ci;
  229. ci.count = dc.first;
  230. ci.creID = dc.second.size() ? dc.second.back() : CreatureID(-1); //should never be accessed
  231. if (ci.creID != CreatureID::NONE)
  232. {
  233. ci.level = ci.creID.toCreature()->getLevel(); //this is creature tier, while tryRealize expects dwelling level. Ignore.
  234. }
  235. else
  236. {
  237. ci.level = 0;
  238. }
  239. return ci;
  240. }
  241. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  242. {
  243. return h1->getTotalStrength() < h2->getTotalStrength();
  244. }
  245. bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2)
  246. {
  247. return a1->getArmyStrength() < a2->getArmyStrength();
  248. }
  249. bool compareArtifacts(const CArtifactInstance * a1, const CArtifactInstance * a2)
  250. {
  251. auto art1 = a1->artType;
  252. auto art2 = a2->artType;
  253. if(art1->getPrice() == art2->getPrice())
  254. return art1->valOfBonuses(BonusType::PRIMARY_SKILL) > art2->valOfBonuses(BonusType::PRIMARY_SKILL);
  255. else
  256. return art1->getPrice() > art2->getPrice();
  257. }
  258. bool isWeeklyRevisitable(const CGObjectInstance * obj)
  259. {
  260. if(!obj)
  261. return false;
  262. //TODO: allow polling of remaining creatures in dwelling
  263. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
  264. return rewardable->configuration.getResetDuration() == 7;
  265. if(dynamic_cast<const CGDwelling *>(obj))
  266. return true;
  267. switch(obj->ID)
  268. {
  269. case Obj::HILL_FORT:
  270. return true;
  271. case Obj::BORDER_GATE:
  272. case Obj::BORDERGUARD:
  273. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  274. }
  275. return false;
  276. }
  277. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start)
  278. {
  279. auto end = std::chrono::high_resolution_clock::now();
  280. return std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  281. }
  282. // todo: move to obj manager
  283. bool shouldVisit(const Nullkiller * ai, const CGHeroInstance * h, const CGObjectInstance * obj)
  284. {
  285. auto relations = ai->cb->getPlayerRelations(obj->tempOwner, h->tempOwner);
  286. switch(obj->ID)
  287. {
  288. case Obj::TOWN:
  289. case Obj::HERO: //never visit our heroes at random
  290. return relations == PlayerRelations::ENEMIES; //do not visit our towns at random
  291. case Obj::BORDER_GATE:
  292. {
  293. for(auto q : ai->cb->getMyQuests())
  294. {
  295. if(q.obj == obj)
  296. {
  297. return false; // do not visit guards or gates when wandering
  298. }
  299. }
  300. return true; //we don't have this quest yet
  301. }
  302. case Obj::BORDERGUARD: //open borderguard if possible
  303. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  304. case Obj::SEER_HUT:
  305. {
  306. for(auto q : ai->cb->getMyQuests())
  307. {
  308. if(q.obj == obj)
  309. {
  310. if(q.quest->checkQuest(h))
  311. return true; //we completed the quest
  312. else
  313. return false; //we can't complete this quest
  314. }
  315. }
  316. return true; //we don't have this quest yet
  317. }
  318. case Obj::CREATURE_GENERATOR1:
  319. {
  320. if(relations == PlayerRelations::ENEMIES)
  321. return true; //flag just in case
  322. if(relations == PlayerRelations::ALLIES)
  323. return false;
  324. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  325. for(auto level : d->creatures)
  326. {
  327. for(auto c : level.second)
  328. {
  329. if(level.first
  330. && h->getSlotFor(CreatureID(c)) != SlotID()
  331. && ai->cb->getResourceAmount().canAfford(c.toCreature()->getFullRecruitCost()))
  332. {
  333. return true;
  334. }
  335. }
  336. }
  337. return false;
  338. }
  339. case Obj::HILL_FORT:
  340. {
  341. for(auto slot : h->Slots())
  342. {
  343. if(slot.second->type->hasUpgrades())
  344. return true; //TODO: check price?
  345. }
  346. return false;
  347. }
  348. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  349. case Obj::MONOLITH_ONE_WAY_EXIT:
  350. case Obj::MONOLITH_TWO_WAY:
  351. case Obj::WHIRLPOOL:
  352. return false;
  353. case Obj::SCHOOL_OF_MAGIC:
  354. case Obj::SCHOOL_OF_WAR:
  355. {
  356. if(ai->getFreeGold() < 1000)
  357. return false;
  358. break;
  359. }
  360. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  361. if(h->level < 10)
  362. return false;
  363. break;
  364. case Obj::TREE_OF_KNOWLEDGE:
  365. {
  366. if(ai->heroManager->getHeroRole(h) == HeroRole::SCOUT)
  367. return false;
  368. TResources myRes = ai->getFreeResources();
  369. if(myRes[EGameResID::GOLD] < 2000 || myRes[EGameResID::GEMS] < 10)
  370. return false;
  371. break;
  372. }
  373. case Obj::MAGIC_WELL:
  374. return h->mana < h->manaLimit();
  375. case Obj::PRISON:
  376. return ai->cb->getHeroesInfo().size() < VLC->settings()->getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP);
  377. case Obj::TAVERN:
  378. case Obj::EYE_OF_MAGI:
  379. case Obj::BOAT:
  380. case Obj::SIGN:
  381. return false;
  382. }
  383. if(obj->wasVisited(h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  384. return false;
  385. return true;
  386. }
  387. bool townHasFreeTavern(const CGTownInstance * town)
  388. {
  389. if(!town->hasBuilt(BuildingID::TAVERN)) return false;
  390. if(!town->visitingHero) return true;
  391. bool canMoveVisitingHeroToGarnison = !town->getUpperArmy()->stacksCount();
  392. return canMoveVisitingHeroToGarnison;
  393. }
  394. }