AIUtility.h 7.2 KB

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