Global.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /*
  2. * Global.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. /* ---------------------------------------------------------------------------- */
  12. /* Compiler detection */
  13. /* ---------------------------------------------------------------------------- */
  14. // Fixed width bool data type is important for serialization
  15. static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size.");
  16. #if defined _M_X64 && defined _WIN32 //Win64 -> cannot load 32-bit DLLs for video handling
  17. #define DISABLE_VIDEO
  18. #endif
  19. #ifdef __GNUC__
  20. #define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__)
  21. #endif
  22. #if defined(__GNUC__) && (GCC_VERSION == 470 || GCC_VERSION == 471)
  23. #error This GCC version has buggy std::array::at version and should not be used. Please update to 4.7.2 or use 4.6.x.
  24. #endif
  25. /* ---------------------------------------------------------------------------- */
  26. /* Guarantee compiler features */
  27. /* ---------------------------------------------------------------------------- */
  28. //defining available c++11 features
  29. //initialization lists - only gcc-4.4 or later
  30. #if defined(__clang__) || defined(__GNUC__)
  31. #define CPP11_USE_INITIALIZERS_LIST
  32. #endif
  33. //nullptr - only msvc and gcc-4.6 or later, othervice define it as nullptr
  34. #if !defined(_MSC_VER) && !(defined(__GNUC__) && (GCC_VERSION >= 460)) && !(defined(__clang__))
  35. #define nullptr NULL
  36. #endif
  37. //override keyword - only msvc and gcc-4.7 or later.
  38. #if !defined(_MSC_VER) && !defined(__clang__) && !(defined(__GNUC__) && (GCC_VERSION >= 470))
  39. #define override
  40. #endif
  41. /* ---------------------------------------------------------------------------- */
  42. /* Suppress some compiler warnings */
  43. /* ---------------------------------------------------------------------------- */
  44. #ifdef _MSC_VER
  45. #pragma warning (disable : 4800 ) /* disable conversion to bool warning -- I think it's intended in all places */
  46. #endif
  47. /* ---------------------------------------------------------------------------- */
  48. /* Commonly used C++, Boost headers */
  49. /* ---------------------------------------------------------------------------- */
  50. #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
  51. #include <cstdio>
  52. #include <stdio.h>
  53. #include <algorithm>
  54. #include <array>
  55. #include <cassert>
  56. #include <climits>
  57. #include <cmath>
  58. #include <cstdlib>
  59. #include <functional>
  60. #include <fstream>
  61. #include <iomanip>
  62. #include <iostream>
  63. #include <map>
  64. #include <memory>
  65. #include <numeric>
  66. #include <queue>
  67. #include <random>
  68. #include <set>
  69. #include <sstream>
  70. #include <string>
  71. #include <utility>
  72. #include <vector>
  73. //The only available version is 3, as of Boost 1.50
  74. #include <boost/version.hpp>
  75. #define BOOST_FILESYSTEM_VERSION 3
  76. #if ( BOOST_VERSION>105000 )
  77. #define BOOST_THREAD_VERSION 3
  78. #endif
  79. #define BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE 1
  80. #define BOOST_BIND_NO_PLACEHOLDERS
  81. //#define BOOST_SYSTEM_NO_DEPRECATED 1
  82. #include <boost/algorithm/string.hpp>
  83. #include <boost/assign.hpp>
  84. #include <boost/cstdint.hpp>
  85. #include <boost/current_function.hpp>
  86. #include <boost/date_time/posix_time/posix_time.hpp>
  87. #include <boost/date_time/posix_time/posix_time_io.hpp>
  88. #include <boost/filesystem.hpp>
  89. #include <boost/foreach.hpp>
  90. #include <boost/format.hpp>
  91. #include <boost/lexical_cast.hpp>
  92. #include <boost/logic/tribool.hpp>
  93. #include <boost/optional.hpp>
  94. #include <boost/program_options.hpp>
  95. #include <boost/range/adaptor/filtered.hpp>
  96. #include <boost/range/algorithm.hpp>
  97. #include <boost/thread.hpp>
  98. #include <boost/unordered_map.hpp>
  99. #include <boost/unordered_set.hpp>
  100. #include <boost/variant.hpp>
  101. #ifdef ANDROID
  102. #include <android/log.h>
  103. #endif
  104. /* ---------------------------------------------------------------------------- */
  105. /* Usings */
  106. /* ---------------------------------------------------------------------------- */
  107. using std::shared_ptr;
  108. using std::unique_ptr;
  109. using std::make_shared;
  110. using namespace std::placeholders;
  111. namespace range = boost::range;
  112. /* ---------------------------------------------------------------------------- */
  113. /* Typedefs */
  114. /* ---------------------------------------------------------------------------- */
  115. // Integral data types
  116. typedef boost::uint64_t ui64; //unsigned int 64 bits (8 bytes)
  117. typedef boost::uint32_t ui32; //unsigned int 32 bits (4 bytes)
  118. typedef boost::uint16_t ui16; //unsigned int 16 bits (2 bytes)
  119. typedef boost::uint8_t ui8; //unsigned int 8 bits (1 byte)
  120. typedef boost::int64_t si64; //signed int 64 bits (8 bytes)
  121. typedef boost::int32_t si32; //signed int 32 bits (4 bytes)
  122. typedef boost::int16_t si16; //signed int 16 bits (2 bytes)
  123. typedef boost::int8_t si8; //signed int 8 bits (1 byte)
  124. // Lock typedefs
  125. typedef boost::lock_guard<boost::mutex> TLockGuard;
  126. typedef boost::lock_guard<boost::recursive_mutex> TLockGuardRec;
  127. /* ---------------------------------------------------------------------------- */
  128. /* Macros */
  129. /* ---------------------------------------------------------------------------- */
  130. // Import + Export macro declarations
  131. #ifdef _WIN32
  132. # ifdef __GNUC__
  133. # define DLL_EXPORT __attribute__((dllexport))
  134. # else
  135. # define DLL_EXPORT __declspec(dllexport)
  136. # endif
  137. #else
  138. # ifdef __GNUC__
  139. # define DLL_EXPORT __attribute__ ((visibility("default")))
  140. # endif
  141. #endif
  142. #ifdef _WIN32
  143. # ifdef __GNUC__
  144. # define DLL_IMPORT __attribute__((dllimport))
  145. # else
  146. # define DLL_IMPORT __declspec(dllimport)
  147. # endif
  148. #else
  149. # ifdef __GNUC__
  150. # define DLL_IMPORT __attribute__ ((visibility("default")))
  151. # endif
  152. #endif
  153. #ifdef VCMI_DLL
  154. # define DLL_LINKAGE DLL_EXPORT
  155. #else
  156. # define DLL_LINKAGE DLL_IMPORT
  157. #endif
  158. #define THROW_FORMAT(message, formatting_elems) throw std::runtime_error(boost::str(boost::format(message) % formatting_elems))
  159. #define ASSERT_IF_CALLED_WITH_PLAYER if(!player) {logGlobal->errorStream() << BOOST_CURRENT_FUNCTION; assert(0);}
  160. //XXX pls dont - 'debug macros' are usually more trouble than it's worth
  161. #define HANDLE_EXCEPTION \
  162. catch (const std::exception& e) { \
  163. logGlobal->errorStream() << e.what(); \
  164. throw; \
  165. } \
  166. catch (const std::exception * e) \
  167. { \
  168. logGlobal->errorStream() << e->what(); \
  169. throw; \
  170. } \
  171. catch (const std::string& e) { \
  172. logGlobal->errorStream() << e; \
  173. throw; \
  174. }
  175. #define HANDLE_EXCEPTIONC(COMMAND) \
  176. catch (const std::exception& e) { \
  177. COMMAND; \
  178. logGlobal->errorStream() << e.what(); \
  179. throw; \
  180. } \
  181. catch (const std::string &e) \
  182. { \
  183. COMMAND; \
  184. logGlobal->errorStream() << e; \
  185. throw; \
  186. }
  187. // can be used for counting arrays
  188. template<typename T, size_t N> char (&_ArrayCountObj(const T (&)[N]))[N];
  189. #define ARRAY_COUNT(arr) (sizeof(_ArrayCountObj(arr)))
  190. /* ---------------------------------------------------------------------------- */
  191. /* VCMI standard library */
  192. /* ---------------------------------------------------------------------------- */
  193. //a normal std::map with a const operator[] for sanity
  194. template<typename KeyT, typename ValT>
  195. class bmap : public std::map<KeyT, ValT>
  196. {
  197. public:
  198. const ValT & operator[](KeyT key) const
  199. {
  200. return this->find(key)->second;
  201. }
  202. ValT & operator[](KeyT key)
  203. {
  204. return static_cast<std::map<KeyT, ValT> &>(*this)[key];
  205. }
  206. template <typename Handler> void serialize(Handler &h, const int version)
  207. {
  208. h & static_cast<std::map<KeyT, ValT> &>(*this);
  209. }
  210. bmap()
  211. {}
  212. explicit bmap(const typename std::map<KeyT, ValT>::key_compare& _Pred)
  213. : std::map<KeyT, ValT>(_Pred)
  214. {}
  215. bmap(const typename std::map<KeyT, ValT>::key_compare& _Pred, const typename std::map<KeyT, ValT>::allocator_type& _Al)
  216. : std::map<KeyT, ValT>(_Pred, _Al)
  217. {}
  218. template<class _Iter>
  219. bmap(_Iter _First, _Iter _Last)
  220. : std::map<KeyT, ValT>(_First, _Last)
  221. {}
  222. template<class _Iter>
  223. bmap(_Iter _First, _Iter _Last,
  224. const typename std::map<KeyT, ValT>::key_compare& _Pred)
  225. : std::map<KeyT, ValT>(_First, _Last, _Pred)
  226. {}
  227. template<class _Iter>
  228. bmap(_Iter _First, _Iter _Last,
  229. const typename std::map<KeyT, ValT>::key_compare& _Pred, const typename std::map<KeyT, ValT>::allocator_type& _Al)
  230. : std::map<KeyT, ValT>(_First, _Last, _Pred, _Al)
  231. {}
  232. };
  233. namespace vstd
  234. {
  235. //returns true if container c contains item i
  236. template <typename Container, typename Item>
  237. bool contains(const Container & c, const Item &i)
  238. {
  239. return std::find(boost::begin(c), boost::end(c),i) != boost::end(c);
  240. }
  241. //returns true if container c contains item i
  242. template <typename Container, typename Pred>
  243. bool contains_if(const Container & c, Pred p)
  244. {
  245. return std::find_if(boost::begin(c), boost::end(c), p) != boost::end(c);
  246. }
  247. //returns true if map c contains item i
  248. template <typename V, typename Item, typename Item2>
  249. bool contains(const std::map<Item,V> & c, const Item2 &i)
  250. {
  251. return c.find(i)!=c.end();
  252. }
  253. //returns true if bmap c contains item i
  254. template <typename V, typename Item, typename Item2>
  255. bool contains(const bmap<Item,V> & c, const Item2 &i)
  256. {
  257. return c.find(i)!=c.end();
  258. }
  259. //returns true if unordered set c contains item i
  260. template <typename Item>
  261. bool contains(const boost::unordered_set<Item> & c, const Item &i)
  262. {
  263. return c.find(i)!=c.end();
  264. }
  265. template <typename V, typename Item, typename Item2>
  266. bool contains(const boost::unordered_map<Item,V> & c, const Item2 &i)
  267. {
  268. return c.find(i)!=c.end();
  269. }
  270. //returns position of first element in vector c equal to s, if there is no such element, -1 is returned
  271. template <typename Container, typename T2>
  272. int find_pos(const Container & c, const T2 &s)
  273. {
  274. size_t i=0;
  275. for (auto iter = boost::begin(c); iter != boost::end(c); iter++, i++)
  276. if(*iter == s)
  277. return i;
  278. return -1;
  279. }
  280. //Func(T1,T2) must say if these elements matches
  281. template <typename T1, typename T2, typename Func>
  282. int find_pos(const std::vector<T1> & c, const T2 &s, const Func &f)
  283. {
  284. for(size_t i=0; i < c.size(); ++i)
  285. if(f(c[i],s))
  286. return i;
  287. return -1;
  288. }
  289. //returns iterator to the given element if present in container, end() if not
  290. template <typename Container, typename Item>
  291. typename Container::iterator find(Container & c, const Item &i)
  292. {
  293. return std::find(c.begin(),c.end(),i);
  294. }
  295. //returns const iterator to the given element if present in container, end() if not
  296. template <typename Container, typename Item>
  297. typename Container::const_iterator find(const Container & c, const Item &i)
  298. {
  299. return std::find(c.begin(),c.end(),i);
  300. }
  301. //removes element i from container c, returns false if c does not contain i
  302. template <typename Container, typename Item>
  303. typename Container::size_type operator-=(Container &c, const Item &i)
  304. {
  305. typename Container::iterator itr = find(c,i);
  306. if(itr == c.end())
  307. return false;
  308. c.erase(itr);
  309. return true;
  310. }
  311. //assigns greater of (a, b) to a and returns maximum of (a, b)
  312. template <typename t1, typename t2>
  313. t1 &amax(t1 &a, const t2 &b)
  314. {
  315. if(a >= b)
  316. return a;
  317. else
  318. {
  319. a = b;
  320. return a;
  321. }
  322. }
  323. //assigns smaller of (a, b) to a and returns minimum of (a, b)
  324. template <typename t1, typename t2>
  325. t1 &amin(t1 &a, const t2 &b)
  326. {
  327. if(a <= b)
  328. return a;
  329. else
  330. {
  331. a = b;
  332. return a;
  333. }
  334. }
  335. //makes a to fit the range <b, c>
  336. template <typename t1, typename t2, typename t3>
  337. t1 &abetween(t1 &a, const t2 &b, const t3 &c)
  338. {
  339. amax(a,b);
  340. amin(a,c);
  341. return a;
  342. }
  343. //checks if a is between b and c
  344. template <typename t1, typename t2, typename t3>
  345. bool isbetween(const t1 &value, const t2 &min, const t3 &max)
  346. {
  347. return value > min && value < max;
  348. }
  349. //checks if a is within b and c
  350. template <typename t1, typename t2, typename t3>
  351. bool iswithin(const t1 &value, const t2 &min, const t3 &max)
  352. {
  353. return value >= min && value <= max;
  354. }
  355. template <typename t1, typename t2>
  356. struct assigner
  357. {
  358. public:
  359. t1 &op1;
  360. t2 op2;
  361. assigner(t1 &a1, const t2 & a2)
  362. :op1(a1), op2(a2)
  363. {}
  364. void operator()()
  365. {
  366. op1 = op2;
  367. }
  368. };
  369. // Assigns value a2 to a1. The point of time of the real operation can be controlled
  370. // with the () operator.
  371. template <typename t1, typename t2>
  372. assigner<t1,t2> assigno(t1 &a1, const t2 &a2)
  373. {
  374. return assigner<t1,t2>(a1,a2);
  375. }
  376. //deleted pointer and sets it to nullptr
  377. template <typename T>
  378. void clear_pointer(T* &ptr)
  379. {
  380. delete ptr;
  381. ptr = nullptr;
  382. }
  383. template<typename T>
  384. std::unique_ptr<T> make_unique()
  385. {
  386. return std::unique_ptr<T>(new T());
  387. }
  388. template<typename T, typename Arg1>
  389. std::unique_ptr<T> make_unique(Arg1 &&arg1)
  390. {
  391. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1)));
  392. }
  393. template<typename T, typename Arg1, typename Arg2>
  394. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2)
  395. {
  396. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)));
  397. }
  398. template<typename T, typename Arg1, typename Arg2, typename Arg3>
  399. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3)
  400. {
  401. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)));
  402. }
  403. template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  404. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3, Arg4 &&arg4)
  405. {
  406. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)));
  407. }
  408. template <typename Container>
  409. typename Container::const_reference circularAt(const Container &r, size_t index)
  410. {
  411. assert(r.size());
  412. index %= r.size();
  413. auto itr = boost::begin(r);
  414. std::advance(itr, index);
  415. return *itr;
  416. }
  417. template<typename Range, typename Predicate>
  418. void erase_if(Range &vec, Predicate pred)
  419. {
  420. vec.erase(boost::remove_if(vec, pred),vec.end());
  421. }
  422. template<typename Elem, typename Predicate>
  423. void erase_if(std::set<Elem> &setContainer, Predicate pred)
  424. {
  425. auto itr = setContainer.begin();
  426. auto endItr = setContainer.end();
  427. while(itr != endItr)
  428. {
  429. auto tmpItr = itr++;
  430. if(pred(*tmpItr))
  431. setContainer.erase(tmpItr);
  432. }
  433. }
  434. //works for map and bmap, maybe something else
  435. template<typename Key, typename Val, typename Predicate>
  436. void erase_if(std::map<Key, Val> &container, Predicate pred)
  437. {
  438. auto itr = container.begin();
  439. auto endItr = container.end();
  440. while(itr != endItr)
  441. {
  442. auto tmpItr = itr++;
  443. if(pred(*tmpItr))
  444. container.erase(tmpItr);
  445. }
  446. }
  447. template<typename InputRange, typename OutputIterator, typename Predicate>
  448. OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
  449. {
  450. return std::copy_if(boost::const_begin(input), boost::end(input), result, pred);
  451. }
  452. template <typename Container>
  453. std::insert_iterator<Container> set_inserter(Container &c)
  454. {
  455. return std::inserter(c, c.end());
  456. }
  457. //Returns iterator to the element for which the value of ValueFunction is minimal
  458. template<class ForwardRange, class ValueFunction>
  459. auto minElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(boost::begin(rng))
  460. {
  461. typedef decltype(*boost::begin(rng)) ElemType;
  462. return boost::min_element(rng, [&] (ElemType lhs, ElemType rhs) -> bool
  463. {
  464. return vf(lhs) < vf(rhs);
  465. });
  466. }
  467. //Returns iterator to the element for which the value of ValueFunction is maximal
  468. template<class ForwardRange, class ValueFunction>
  469. auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(boost::begin(rng))
  470. {
  471. typedef decltype(*boost::begin(rng)) ElemType;
  472. return boost::max_element(rng, [&] (ElemType lhs, ElemType rhs) -> bool
  473. {
  474. return vf(lhs) < vf(rhs);
  475. });
  476. }
  477. static inline int retreiveRandNum(const std::function<int()> &randGen)
  478. {
  479. if (randGen)
  480. return randGen();
  481. else
  482. return rand();
  483. }
  484. template <typename T> const T & pickRandomElementOf(const std::vector<T> &v, const std::function<int()> &randGen)
  485. {
  486. return v.at(retreiveRandNum(randGen) % v.size());
  487. }
  488. template<typename T>
  489. void advance(T &obj, int change)
  490. {
  491. obj = (T)(((int)obj) + change);
  492. }
  493. template <typename Container>
  494. typename Container::value_type backOrNull(const Container &c) //returns last element of container or nullptr if it is empty (to be used with containers of pointers)
  495. {
  496. if(c.size())
  497. return c.back();
  498. else
  499. return typename Container::value_type();
  500. }
  501. template <typename Container>
  502. typename Container::value_type frontOrNull(const Container &c) //returns first element of container or nullptr if it is empty (to be used with containers of pointers)
  503. {
  504. if(c.size())
  505. return c.front();
  506. else
  507. return nullptr;
  508. }
  509. }
  510. using vstd::operator-=;
  511. using vstd::make_unique;
  512. /* ---------------------------------------------------------------------------- */
  513. /* VCMI headers */
  514. /* ---------------------------------------------------------------------------- */
  515. #include "lib/logging/CLogger.h"