AIUtility.h 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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/VCMI_Lib.h"
  37. #include "../../lib/CBuildingHandler.h"
  38. #include "../../lib/CCreatureHandler.h"
  39. #include "../../lib/CTownHandler.h"
  40. #include "../../lib/spells/CSpellHandler.h"
  41. #include "../../lib/CStopWatch.h"
  42. #include "../../lib/mapObjects/CObjectHandler.h"
  43. #include "../../lib/mapObjects/CGHeroInstance.h"
  44. #include "../../lib/CPathfinder.h"
  45. #include <chrono>
  46. using namespace tbb;
  47. class CCallback;
  48. class Nullkiller;
  49. struct creInfo;
  50. typedef const int3 & crint3;
  51. typedef const std::string & crstring;
  52. typedef std::pair<ui32, std::vector<CreatureID>> dwellingContent;
  53. const int GOLD_MINE_PRODUCTION = 1000, WOOD_ORE_MINE_PRODUCTION = 2, RESOURCE_MINE_PRODUCTION = 1;
  54. const int ACTUAL_RESOURCE_COUNT = 7;
  55. const int ALLOWED_ROAMING_HEROES = 8;
  56. //implementation-dependent
  57. extern const float SAFE_ATTACK_CONSTANT;
  58. extern const int GOLD_RESERVE;
  59. extern boost::thread_specific_ptr<CCallback> cb;
  60. enum HeroRole
  61. {
  62. SCOUT = 0,
  63. MAIN = 1
  64. };
  65. //provisional class for AI to store a reference to an owned hero object
  66. //checks if it's valid on access, should be used in place of const CGHeroInstance*
  67. struct DLL_EXPORT HeroPtr
  68. {
  69. const CGHeroInstance * h;
  70. ObjectInstanceID hid;
  71. public:
  72. std::string name;
  73. HeroPtr();
  74. HeroPtr(const CGHeroInstance * H);
  75. ~HeroPtr();
  76. operator bool() const
  77. {
  78. return validAndSet();
  79. }
  80. bool operator<(const HeroPtr & rhs) const;
  81. const CGHeroInstance * operator->() const;
  82. const CGHeroInstance * operator*() const; //not that consistent with -> but all interfaces use CGHeroInstance*, so it's convenient
  83. bool operator==(const HeroPtr & rhs) const;
  84. bool operator!=(const HeroPtr & rhs) const
  85. {
  86. return !(*this == rhs);
  87. }
  88. const CGHeroInstance * get(bool doWeExpectNull = false) const;
  89. const CGHeroInstance * get(CCallback * cb, bool doWeExpectNull = false) const;
  90. bool validAndSet() const;
  91. template<typename Handler> void serialize(Handler & h, const int version)
  92. {
  93. h & this->h;
  94. h & hid;
  95. h & name;
  96. }
  97. };
  98. enum BattleState
  99. {
  100. NO_BATTLE,
  101. UPCOMING_BATTLE,
  102. ONGOING_BATTLE,
  103. ENDING_BATTLE
  104. };
  105. // AI lives in a dangerous world. CGObjectInstances under pointer may got deleted/hidden.
  106. // This class stores object id, so we can detect when we lose access to the underlying object.
  107. struct ObjectIdRef
  108. {
  109. ObjectInstanceID id;
  110. const CGObjectInstance * operator->() const;
  111. operator const CGObjectInstance *() const;
  112. operator bool() const;
  113. ObjectIdRef(ObjectInstanceID _id);
  114. ObjectIdRef(const CGObjectInstance * obj);
  115. bool operator<(const ObjectIdRef & rhs) const;
  116. template<typename Handler> void serialize(Handler & h, const int version)
  117. {
  118. h & id;
  119. }
  120. };
  121. struct TimeCheck
  122. {
  123. CStopWatch time;
  124. std::string txt;
  125. TimeCheck(crstring TXT)
  126. : txt(TXT)
  127. {
  128. }
  129. ~TimeCheck()
  130. {
  131. logAi->trace("Time of %s was %d ms.", txt, time.getDiff());
  132. }
  133. };
  134. //TODO: replace with vstd::
  135. struct AtScopeExit
  136. {
  137. std::function<void()> foo;
  138. AtScopeExit(const std::function<void()> & FOO)
  139. : foo(FOO)
  140. {}
  141. ~AtScopeExit()
  142. {
  143. foo();
  144. }
  145. };
  146. class ObjsVector : public std::vector<ObjectIdRef>
  147. {
  148. };
  149. template<int id>
  150. bool objWithID(const CGObjectInstance * obj)
  151. {
  152. return obj->ID == id;
  153. }
  154. struct creInfo
  155. {
  156. int count;
  157. CreatureID creID;
  158. CCreature * cre;
  159. int level;
  160. };
  161. creInfo infoFromDC(const dwellingContent & dc);
  162. template<class Func>
  163. void foreach_tile_pos(const Func & foo)
  164. {
  165. // some micro-optimizations since this function gets called a LOT
  166. // callback pointer is thread-specific and slow to retrieve -> read map size only once
  167. int3 mapSize = cb->getMapSize();
  168. for(int z = 0; z < mapSize.z; z++)
  169. {
  170. for(int x = 0; x < mapSize.x; x++)
  171. {
  172. for(int y = 0; y < mapSize.y; y++)
  173. {
  174. foo(int3(x, y, z));
  175. }
  176. }
  177. }
  178. }
  179. template<class Func>
  180. void foreach_tile_pos(CCallback * cbp, const Func & foo) // avoid costly retrieval of thread-specific pointer
  181. {
  182. int3 mapSize = cbp->getMapSize();
  183. for(int z = 0; z < mapSize.z; z++)
  184. {
  185. for(int x = 0; x < mapSize.x; x++)
  186. {
  187. for(int y = 0; y < mapSize.y; y++)
  188. {
  189. foo(cbp, int3(x, y, z));
  190. }
  191. }
  192. }
  193. }
  194. template<class Func>
  195. void foreach_neighbour(const int3 & pos, const Func & foo)
  196. {
  197. CCallback * cbp = cb.get(); // avoid costly retrieval of thread-specific pointer
  198. for(const int3 & dir : int3::getDirs())
  199. {
  200. const int3 n = pos + dir;
  201. if(cbp->isInTheMap(n))
  202. foo(pos + dir);
  203. }
  204. }
  205. template<class Func>
  206. void foreach_neighbour(CCallback * cbp, const int3 & pos, const Func & foo) // avoid costly retrieval of thread-specific pointer
  207. {
  208. for(const int3 & dir : int3::getDirs())
  209. {
  210. const int3 n = pos + dir;
  211. if(cbp->isInTheMap(n))
  212. foo(cbp, pos + dir);
  213. }
  214. }
  215. bool canBeEmbarkmentPoint(const TerrainTile * t, bool fromWater);
  216. bool isObjectPassable(const CGObjectInstance * obj);
  217. bool isObjectPassable(const Nullkiller * ai, const CGObjectInstance * obj);
  218. bool isObjectPassable(const CGObjectInstance * obj, PlayerColor playerColor, PlayerRelations::PlayerRelations objectRelations);
  219. bool isBlockVisitObj(const int3 & pos);
  220. bool isWeeklyRevisitable(const CGObjectInstance * obj);
  221. bool isObjectRemovable(const CGObjectInstance * obj); //FIXME FIXME: move logic to object property!
  222. bool isSafeToVisit(HeroPtr h, uint64_t dangerStrength);
  223. bool isSafeToVisit(HeroPtr h, const CCreatureSet *, uint64_t dangerStrength);
  224. bool compareHeroStrength(HeroPtr h1, HeroPtr h2);
  225. bool compareArmyStrength(const CArmedInstance * a1, const CArmedInstance * a2);
  226. bool compareArtifacts(const CArtifactInstance * a1, const CArtifactInstance * a2);
  227. uint64_t timeElapsed(std::chrono::time_point<std::chrono::high_resolution_clock> start);
  228. // todo: move to obj manager
  229. bool shouldVisit(const Nullkiller * ai, const CGHeroInstance * h, const CGObjectInstance * obj);
  230. template<typename TFunc>
  231. void pforeachTilePos(crint3 mapSize, TFunc fn)
  232. {
  233. for(int z = 0; z < mapSize.z; ++z)
  234. {
  235. parallel_for(blocked_range<size_t>(0, mapSize.x), [&](const blocked_range<size_t>& r)
  236. {
  237. int3 pos(0, 0, z);
  238. for(pos.x = r.begin(); pos.x != r.end(); ++pos.x)
  239. {
  240. for(pos.y = 0; pos.y < mapSize.y; ++pos.y)
  241. {
  242. fn(pos);
  243. }
  244. }
  245. });
  246. }
  247. }
  248. class CDistanceSorter
  249. {
  250. const CGHeroInstance * hero;
  251. public:
  252. CDistanceSorter(const CGHeroInstance * hero)
  253. : hero(hero)
  254. {
  255. }
  256. bool operator()(const CGObjectInstance * lhs, const CGObjectInstance * rhs) const;
  257. };
  258. template <class T>
  259. class SharedPool
  260. {
  261. public:
  262. struct External_Deleter
  263. {
  264. explicit External_Deleter(std::weak_ptr<SharedPool<T>* > pool)
  265. : pool(pool)
  266. {
  267. }
  268. void operator()(T * ptr)
  269. {
  270. std::unique_ptr<T> uptr(ptr);
  271. if(auto pool_ptr = pool.lock())
  272. {
  273. (*pool_ptr.get())->add(std::move(uptr));
  274. }
  275. }
  276. private:
  277. std::weak_ptr<SharedPool<T>* > pool;
  278. };
  279. public:
  280. using ptr_type = std::unique_ptr<T, External_Deleter>;
  281. SharedPool(std::function<std::unique_ptr<T>()> elementFactory)
  282. : elementFactory(elementFactory), pool(), sync(), instance_tracker(new SharedPool<T>*(this))
  283. {}
  284. void add(std::unique_ptr<T> t)
  285. {
  286. boost::lock_guard<boost::mutex> lock(sync);
  287. pool.push_back(std::move(t));
  288. }
  289. ptr_type acquire()
  290. {
  291. boost::lock_guard<boost::mutex> lock(sync);
  292. bool poolIsEmpty = pool.empty();
  293. T * element = poolIsEmpty
  294. ? elementFactory().release()
  295. : pool.back().release();
  296. ptr_type tmp(
  297. element,
  298. External_Deleter(std::weak_ptr<SharedPool<T>*>(instance_tracker)));
  299. if(!poolIsEmpty) pool.pop_back();
  300. return std::move(tmp);
  301. }
  302. bool empty() const
  303. {
  304. return pool.empty();
  305. }
  306. size_t size() const
  307. {
  308. return pool.size();
  309. }
  310. private:
  311. std::vector<std::unique_ptr<T>> pool;
  312. std::function<std::unique_ptr<T>()> elementFactory;
  313. std::shared_ptr<SharedPool<T> *> instance_tracker;
  314. boost::mutex sync;
  315. };