AIUtility.h 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /*
  2. * AIUtility.h, 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. #pragma once
  11. // Check windows
  12. #if _WIN32 || _WIN64
  13. #if _WIN64
  14. #define ENVIRONMENT64
  15. #else
  16. #define ENVIRONMENT32
  17. #endif
  18. #endif
  19. // Check GCC
  20. #if __GNUC__
  21. #if __x86_64__ || __ppc64__
  22. #define ENVIRONMENT64
  23. #else
  24. #define ENVIRONMENT32
  25. #endif
  26. #endif
  27. /*********************** TBB.h ********************/
  28. #include "tbb/blocked_range.h"
  29. #include "tbb/concurrent_hash_map.h"
  30. #include "tbb/concurrent_unordered_map.h"
  31. #include "tbb/concurrent_unordered_set.h"
  32. #include "tbb/concurrent_vector.h"
  33. #include "tbb/parallel_for.h"
  34. #include "tbb/parallel_invoke.h"
  35. /*********************** TBB.h ********************/
  36. #include "../../lib/GameLibrary.h"
  37. #include "../../lib/CCreatureHandler.h"
  38. #include "../../lib/spells/CSpellHandler.h"
  39. #include "../../lib/CStopWatch.h"
  40. #include "../../lib/mapObjects/CGHeroInstance.h"
  41. #include "../../lib/callback/CCallback.h"
  42. #include <chrono>
  43. using dwellingContent = std::pair<ui32, std::vector<CreatureID>>;
  44. namespace NK2AI
  45. {
  46. struct creInfo;
  47. class AIGateway;
  48. class Nullkiller;
  49. const int GOLD_MINE_PRODUCTION = 1000;
  50. const int WOOD_ORE_MINE_PRODUCTION = 2;
  51. const int RESOURCE_MINE_PRODUCTION = 1;
  52. const int ACTUAL_RESOURCE_COUNT = 7;
  53. enum HeroRole
  54. {
  55. SCOUT = 0,
  56. MAIN = 1
  57. };
  58. //provisional class for AI to store a reference to an owned hero object
  59. //checks if it's valid on access, should be used in place of const CGHeroInstance*
  60. struct DLL_EXPORT HeroPtr
  61. {
  62. private:
  63. const CGHeroInstance * hero;
  64. const CPlayerSpecificInfoCallback * cpsic;
  65. bool verify(bool verbose = true) const;
  66. public:
  67. explicit HeroPtr(const CGHeroInstance * input, const CPlayerSpecificInfoCallback * cpsic);
  68. bool operator<(const HeroPtr & rhs) const;
  69. const CGHeroInstance * operator->() const;
  70. const CGHeroInstance * operator*() const; //not that consistent with -> but all interfaces use CGHeroInstance*, so it's convenient
  71. bool operator==(const HeroPtr & rhs) const;
  72. bool operator!=(const HeroPtr & rhs) const
  73. {
  74. return !(*this == rhs);
  75. }
  76. ObjectInstanceID idOrNone() const;
  77. std::string nameOrDefault() const;
  78. const CGHeroInstance * get() const;
  79. const CGHeroInstance * getUnverified() const;
  80. bool isVerified(bool verbose = true) const;
  81. };
  82. enum BattleState
  83. {
  84. NO_BATTLE,
  85. UPCOMING_BATTLE,
  86. ONGOING_BATTLE,
  87. ENDING_BATTLE
  88. };
  89. // AI lives in a dangerous world. CGObjectInstances under pointer may got deleted/hidden.
  90. // This class stores object id, so we can detect when we lose access to the underlying object.
  91. struct ObjectIdRef
  92. {
  93. const ObjectInstanceID id;
  94. const CPlayerSpecificInfoCallback * cpsic;
  95. explicit ObjectIdRef(ObjectInstanceID id, const CPlayerSpecificInfoCallback * cpsic);
  96. const CGObjectInstance * operator->() const;
  97. operator const CGObjectInstance *() const;
  98. operator bool() const;
  99. bool operator<(const ObjectIdRef & rhs) const;
  100. };
  101. template<Obj::Type id>
  102. bool objWithID(const CGObjectInstance * obj)
  103. {
  104. return obj->ID == id;
  105. }
  106. struct creInfo
  107. {
  108. int count;
  109. CreatureID creID;
  110. int level;
  111. };
  112. creInfo infoFromDC(const dwellingContent & dc);
  113. template<class Func>
  114. void foreach_tile_pos(const CCallback & cc, const Func & foo)
  115. {
  116. // some micro-optimizations since this function gets called a LOT
  117. // callback pointer is thread-specific and slow to retrieve -> read map size only once
  118. int3 mapSize = cc.getMapSize();
  119. for(int z = 0; z < mapSize.z; z++)
  120. {
  121. for(int x = 0; x < mapSize.x; x++)
  122. {
  123. for(int y = 0; y < mapSize.y; y++)
  124. {
  125. foo(int3(x, y, z));
  126. }
  127. }
  128. }
  129. }
  130. template<class Func, class TCallback>
  131. void foreach_tile_pos(TCallback * cbp, const Func & foo) // avoid costly retrieval of thread-specific pointer
  132. {
  133. int3 mapSize = cbp->getMapSize();
  134. for(int z = 0; z < mapSize.z; z++)
  135. {
  136. for(int x = 0; x < mapSize.x; x++)
  137. {
  138. for(int y = 0; y < mapSize.y; y++)
  139. {
  140. foo(cbp, int3(x, y, z));
  141. }
  142. }
  143. }
  144. }
  145. template<class Func>
  146. void foreach_neighbour(const CCallback & cc, const int3 & pos, const Func & foo)
  147. {
  148. for(const int3 & dir : int3::getDirs())
  149. {
  150. const int3 n = pos + dir;
  151. if(cc.isInTheMap(n))
  152. foo(pos + dir);
  153. }
  154. }
  155. template<class Func>
  156. void foreach_neighbour(CCallback * cbp, const int3 & pos, const Func & foo) // avoid costly retrieval of thread-specific pointer
  157. {
  158. for(const int3 & dir : int3::getDirs())
  159. {
  160. const int3 n = pos + dir;
  161. if(cbp->isInTheMap(n))
  162. foo(cbp, pos + dir);
  163. }
  164. }
  165. bool isObjectPassable(const Nullkiller * aiNk, const CGObjectInstance * obj);
  166. bool isObjectPassable(const CGObjectInstance * obj, PlayerColor playerColor, PlayerRelations objectRelations);
  167. bool isWeeklyRevisitable(const PlayerColor & playerID, const CGObjectInstance * obj);
  168. bool isObjectRemovable(const CGObjectInstance * obj); //FIXME FIXME: move logic to object property!
  169. bool isSafeToVisit(const CGHeroInstance * h, uint64_t dangerStrength, float safeAttackRatio);
  170. bool isSafeToVisit(const CGHeroInstance * h, const CCreatureSet *, uint64_t dangerStrength, float safeAttackRatio);
  171. bool compareHeroStrength(const CGHeroInstance * h1, const CGHeroInstance * h2);
  172. bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2);
  173. int64_t getArtifactScoreForHero(const CGHeroInstance * hero, const CArtifactInstance * artifact);
  174. int64_t getPotentialArtifactScore(const CArtifact * art);
  175. bool townHasFreeTavern(const CGTownInstance * town);
  176. uint64_t getHeroArmyStrengthWithCommander(const CGHeroInstance * hero, const CCreatureSet * heroArmy, int fortLevel = 0);
  177. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start);
  178. // todo: move to obj manager
  179. bool shouldVisit(const Nullkiller * aiNk, const CGHeroInstance * hero, const CGObjectInstance * obj);
  180. int getDuplicatingSlots(const CArmedInstance * army);
  181. template <class T>
  182. class SharedPool
  183. {
  184. public:
  185. struct External_Deleter
  186. {
  187. explicit External_Deleter(std::weak_ptr<SharedPool<T>* > pool)
  188. : pool(pool)
  189. {
  190. }
  191. void operator()(T * ptr)
  192. {
  193. std::unique_ptr<T> uptr(ptr);
  194. if(auto pool_ptr = pool.lock())
  195. {
  196. (*pool_ptr.get())->add(std::move(uptr));
  197. }
  198. }
  199. private:
  200. std::weak_ptr<SharedPool<T>* > pool;
  201. };
  202. public:
  203. using ptr_type = std::unique_ptr<T, External_Deleter>;
  204. SharedPool(std::function<std::unique_ptr<T>()> elementFactory):
  205. elementFactory(elementFactory), pool(), instance_tracker(new SharedPool<T> *(this))
  206. {}
  207. void add(std::unique_ptr<T> t)
  208. {
  209. std::lock_guard<std::mutex> lock(sync);
  210. pool.push_back(std::move(t));
  211. }
  212. ptr_type acquire()
  213. {
  214. std::lock_guard<std::mutex> lock(sync);
  215. bool poolIsEmpty = pool.empty();
  216. T * element = poolIsEmpty
  217. ? elementFactory().release()
  218. : pool.back().release();
  219. ptr_type tmp(
  220. element,
  221. External_Deleter(std::weak_ptr<SharedPool<T>*>(instance_tracker)));
  222. if(!poolIsEmpty) pool.pop_back();
  223. return tmp;
  224. }
  225. bool empty() const
  226. {
  227. return pool.empty();
  228. }
  229. size_t size() const
  230. {
  231. return pool.size();
  232. }
  233. private:
  234. std::vector<std::unique_ptr<T>> pool;
  235. std::function<std::unique_ptr<T>()> elementFactory;
  236. std::shared_ptr<SharedPool<T> *> instance_tracker;
  237. std::mutex sync;
  238. };
  239. }