Global.h 17 KB

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