Global.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. #define _USE_MATH_DEFINES
  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 <unordered_set>
  72. #include <unordered_map>
  73. #include <utility>
  74. #include <vector>
  75. //The only available version is 3, as of Boost 1.50
  76. #include <boost/version.hpp>
  77. #define BOOST_FILESYSTEM_VERSION 3
  78. #if ( BOOST_VERSION>105000 )
  79. #define BOOST_THREAD_VERSION 3
  80. #endif
  81. #define BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE 1
  82. //#define BOOST_BIND_NO_PLACEHOLDERS
  83. #include <boost/algorithm/string.hpp>
  84. #include <boost/assign.hpp>
  85. #include <boost/cstdint.hpp>
  86. #include <boost/current_function.hpp>
  87. #include <boost/crc.hpp>
  88. #include <boost/date_time/posix_time/posix_time.hpp>
  89. #include <boost/date_time/posix_time/posix_time_io.hpp>
  90. #include <boost/filesystem.hpp>
  91. #include <boost/format.hpp>
  92. #include <boost/lexical_cast.hpp>
  93. #include <boost/logic/tribool.hpp>
  94. #include <boost/optional.hpp>
  95. #include <boost/program_options.hpp>
  96. #include <boost/range/adaptor/filtered.hpp>
  97. #include <boost/range/adaptor/reversed.hpp>
  98. #include <boost/range/algorithm.hpp>
  99. #include <boost/thread.hpp>
  100. #include <boost/variant.hpp>
  101. #include <boost/math/special_functions/round.hpp>
  102. #ifdef ANDROID
  103. #include <android/log.h>
  104. #endif
  105. /* ---------------------------------------------------------------------------- */
  106. /* Usings */
  107. /* ---------------------------------------------------------------------------- */
  108. using std::shared_ptr;
  109. using std::unique_ptr;
  110. using std::make_shared;
  111. //using namespace std::placeholders;
  112. namespace range = boost::range;
  113. /* ---------------------------------------------------------------------------- */
  114. /* Typedefs */
  115. /* ---------------------------------------------------------------------------- */
  116. // Integral data types
  117. typedef boost::uint64_t ui64; //unsigned int 64 bits (8 bytes)
  118. typedef boost::uint32_t ui32; //unsigned int 32 bits (4 bytes)
  119. typedef boost::uint16_t ui16; //unsigned int 16 bits (2 bytes)
  120. typedef boost::uint8_t ui8; //unsigned int 8 bits (1 byte)
  121. typedef boost::int64_t si64; //signed int 64 bits (8 bytes)
  122. typedef boost::int32_t si32; //signed int 32 bits (4 bytes)
  123. typedef boost::int16_t si16; //signed int 16 bits (2 bytes)
  124. typedef boost::int8_t si8; //signed int 8 bits (1 byte)
  125. // Lock typedefs
  126. typedef boost::lock_guard<boost::mutex> TLockGuard;
  127. typedef boost::lock_guard<boost::recursive_mutex> TLockGuardRec;
  128. /* ---------------------------------------------------------------------------- */
  129. /* Macros */
  130. /* ---------------------------------------------------------------------------- */
  131. // Import + Export macro declarations
  132. #ifdef _WIN32
  133. # ifdef __GNUC__
  134. # define DLL_EXPORT __attribute__((dllexport))
  135. # else
  136. # define DLL_EXPORT __declspec(dllexport)
  137. # endif
  138. #else
  139. # ifdef __GNUC__
  140. # define DLL_EXPORT __attribute__ ((visibility("default")))
  141. # endif
  142. #endif
  143. #ifdef _WIN32
  144. # ifdef __GNUC__
  145. # define DLL_IMPORT __attribute__((dllimport))
  146. # else
  147. # define DLL_IMPORT __declspec(dllimport)
  148. # endif
  149. #else
  150. # ifdef __GNUC__
  151. # define DLL_IMPORT __attribute__ ((visibility("default")))
  152. # endif
  153. #endif
  154. #ifdef VCMI_DLL
  155. # define DLL_LINKAGE DLL_EXPORT
  156. #else
  157. # define DLL_LINKAGE DLL_IMPORT
  158. #endif
  159. #define THROW_FORMAT(message, formatting_elems) throw std::runtime_error(boost::str(boost::format(message) % formatting_elems))
  160. #define ASSERT_IF_CALLED_WITH_PLAYER if(!player) {logGlobal->errorStream() << BOOST_CURRENT_FUNCTION; assert(0);}
  161. //XXX pls dont - 'debug macros' are usually more trouble than it's worth
  162. #define HANDLE_EXCEPTION \
  163. catch (const std::exception& e) { \
  164. logGlobal->errorStream() << e.what(); \
  165. throw; \
  166. } \
  167. catch (const std::exception * e) \
  168. { \
  169. logGlobal->errorStream() << e->what(); \
  170. throw; \
  171. } \
  172. catch (const std::string& e) { \
  173. logGlobal->errorStream() << e; \
  174. throw; \
  175. }
  176. #define HANDLE_EXCEPTIONC(COMMAND) \
  177. catch (const std::exception& e) { \
  178. COMMAND; \
  179. logGlobal->errorStream() << e.what(); \
  180. throw; \
  181. } \
  182. catch (const std::string &e) \
  183. { \
  184. COMMAND; \
  185. logGlobal->errorStream() << e; \
  186. throw; \
  187. }
  188. // can be used for counting arrays
  189. template<typename T, size_t N> char (&_ArrayCountObj(const T (&)[N]))[N];
  190. #define ARRAY_COUNT(arr) (sizeof(_ArrayCountObj(arr)))
  191. // should be used for variables that becomes unused in release builds (e.g. only used for assert checks)
  192. #define UNUSED(VAR) ((void)VAR)
  193. /* ---------------------------------------------------------------------------- */
  194. /* VCMI standard library */
  195. /* ---------------------------------------------------------------------------- */
  196. //a normal std::map with a const operator[] for sanity
  197. template<typename KeyT, typename ValT>
  198. class bmap : public std::map<KeyT, ValT>
  199. {
  200. public:
  201. const ValT & operator[](KeyT key) const
  202. {
  203. return this->find(key)->second;
  204. }
  205. ValT & operator[](KeyT key)
  206. {
  207. return static_cast<std::map<KeyT, ValT> &>(*this)[key];
  208. }
  209. template <typename Handler> void serialize(Handler &h, const int version)
  210. {
  211. h & static_cast<std::map<KeyT, ValT> &>(*this);
  212. }
  213. bmap()
  214. {}
  215. explicit bmap(const typename std::map<KeyT, ValT>::key_compare& _Pred)
  216. : std::map<KeyT, ValT>(_Pred)
  217. {}
  218. bmap(const typename std::map<KeyT, ValT>::key_compare& _Pred, const typename std::map<KeyT, ValT>::allocator_type& _Al)
  219. : std::map<KeyT, ValT>(_Pred, _Al)
  220. {}
  221. template<class _Iter>
  222. bmap(_Iter _First, _Iter _Last)
  223. : std::map<KeyT, ValT>(_First, _Last)
  224. {}
  225. template<class _Iter>
  226. bmap(_Iter _First, _Iter _Last,
  227. const typename std::map<KeyT, ValT>::key_compare& _Pred)
  228. : std::map<KeyT, ValT>(_First, _Last, _Pred)
  229. {}
  230. template<class _Iter>
  231. bmap(_Iter _First, _Iter _Last,
  232. const typename std::map<KeyT, ValT>::key_compare& _Pred, const typename std::map<KeyT, ValT>::allocator_type& _Al)
  233. : std::map<KeyT, ValT>(_First, _Last, _Pred, _Al)
  234. {}
  235. };
  236. template<typename T>
  237. std::ostream &operator<<(std::ostream &out, const boost::optional<T> &opt)
  238. {
  239. if(opt)
  240. return out << *opt;
  241. else
  242. return out<< "empty";
  243. }
  244. namespace vstd
  245. {
  246. // combine hashes. Present in boost but not in std
  247. template <class T>
  248. inline void hash_combine(std::size_t& seed, const T& v)
  249. {
  250. std::hash<T> hasher;
  251. seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
  252. }
  253. //returns true if container c contains item i
  254. template <typename Container, typename Item>
  255. bool contains(const Container & c, const Item &i)
  256. {
  257. return std::find(std::begin(c), std::end(c),i) != std::end(c);
  258. }
  259. //returns true if container c contains item i
  260. template <typename Container, typename Pred>
  261. bool contains_if(const Container & c, Pred p)
  262. {
  263. return std::find_if(std::begin(c), std::end(c), p) != std::end(c);
  264. }
  265. //returns true if map c contains item i
  266. template <typename V, typename Item, typename Item2>
  267. bool contains(const std::map<Item,V> & c, const Item2 &i)
  268. {
  269. return c.find(i)!=c.end();
  270. }
  271. //returns true if bmap c contains item i
  272. template <typename V, typename Item, typename Item2>
  273. bool contains(const bmap<Item,V> & c, const Item2 &i)
  274. {
  275. return c.find(i)!=c.end();
  276. }
  277. //returns true if unordered set c contains item i
  278. template <typename Item>
  279. bool contains(const std::unordered_set<Item> & c, const Item &i)
  280. {
  281. return c.find(i)!=c.end();
  282. }
  283. template <typename V, typename Item, typename Item2>
  284. bool contains(const std::unordered_map<Item,V> & c, const Item2 &i)
  285. {
  286. return c.find(i)!=c.end();
  287. }
  288. //returns position of first element in vector c equal to s, if there is no such element, -1 is returned
  289. template <typename Container, typename T2>
  290. int find_pos(const Container & c, const T2 &s)
  291. {
  292. size_t i=0;
  293. for (auto iter = std::begin(c); iter != std::end(c); iter++, i++)
  294. if(*iter == s)
  295. return i;
  296. return -1;
  297. }
  298. //Func f tells if element matches
  299. template <typename Container, typename Func>
  300. int find_pos_if(const Container & c, const Func &f)
  301. {
  302. auto ret = boost::range::find_if(c, f);
  303. if(ret != std::end(c))
  304. return std::distance(std::begin(c), ret);
  305. return -1;
  306. }
  307. //returns iterator to the given element if present in container, end() if not
  308. template <typename Container, typename Item>
  309. typename Container::iterator find(Container & c, const Item &i)
  310. {
  311. return std::find(c.begin(),c.end(),i);
  312. }
  313. //returns const iterator to the given element if present in container, end() if not
  314. template <typename Container, typename Item>
  315. typename Container::const_iterator find(const Container & c, const Item &i)
  316. {
  317. return std::find(c.begin(),c.end(),i);
  318. }
  319. //removes element i from container c, returns false if c does not contain i
  320. template <typename Container, typename Item>
  321. typename Container::size_type operator-=(Container &c, const Item &i)
  322. {
  323. typename Container::iterator itr = find(c,i);
  324. if(itr == c.end())
  325. return false;
  326. c.erase(itr);
  327. return true;
  328. }
  329. //assigns greater of (a, b) to a and returns maximum of (a, b)
  330. template <typename t1, typename t2>
  331. t1 &amax(t1 &a, const t2 &b)
  332. {
  333. if(a >= b)
  334. return a;
  335. else
  336. {
  337. a = b;
  338. return a;
  339. }
  340. }
  341. //assigns smaller of (a, b) to a and returns minimum of (a, b)
  342. template <typename t1, typename t2>
  343. t1 &amin(t1 &a, const t2 &b)
  344. {
  345. if(a <= b)
  346. return a;
  347. else
  348. {
  349. a = b;
  350. return a;
  351. }
  352. }
  353. //makes a to fit the range <b, c>
  354. template <typename t1, typename t2, typename t3>
  355. t1 &abetween(t1 &a, const t2 &b, const t3 &c)
  356. {
  357. amax(a,b);
  358. amin(a,c);
  359. return a;
  360. }
  361. //checks if a is between b and c
  362. template <typename t1, typename t2, typename t3>
  363. bool isbetween(const t1 &value, const t2 &min, const t3 &max)
  364. {
  365. return value > min && value < max;
  366. }
  367. //checks if a is within b and c
  368. template <typename t1, typename t2, typename t3>
  369. bool iswithin(const t1 &value, const t2 &min, const t3 &max)
  370. {
  371. return value >= min && value <= max;
  372. }
  373. template <typename t1, typename t2>
  374. struct assigner
  375. {
  376. public:
  377. t1 &op1;
  378. t2 op2;
  379. assigner(t1 &a1, const t2 & a2)
  380. :op1(a1), op2(a2)
  381. {}
  382. void operator()()
  383. {
  384. op1 = op2;
  385. }
  386. };
  387. // Assigns value a2 to a1. The point of time of the real operation can be controlled
  388. // with the () operator.
  389. template <typename t1, typename t2>
  390. assigner<t1,t2> assigno(t1 &a1, const t2 &a2)
  391. {
  392. return assigner<t1,t2>(a1,a2);
  393. }
  394. //deleted pointer and sets it to nullptr
  395. template <typename T>
  396. void clear_pointer(T* &ptr)
  397. {
  398. delete ptr;
  399. ptr = nullptr;
  400. }
  401. #if _MSC_VER >= 1800
  402. using std::make_unique;
  403. #else
  404. template<typename T>
  405. std::unique_ptr<T> make_unique()
  406. {
  407. return std::unique_ptr<T>(new T());
  408. }
  409. template<typename T, typename Arg1>
  410. std::unique_ptr<T> make_unique(Arg1 &&arg1)
  411. {
  412. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1)));
  413. }
  414. template<typename T, typename Arg1, typename Arg2>
  415. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2)
  416. {
  417. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)));
  418. }
  419. template<typename T, typename Arg1, typename Arg2, typename Arg3>
  420. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3)
  421. {
  422. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)));
  423. }
  424. template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  425. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3, Arg4 &&arg4)
  426. {
  427. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)));
  428. }
  429. #endif
  430. template <typename Container>
  431. typename Container::const_reference circularAt(const Container &r, size_t index)
  432. {
  433. assert(r.size());
  434. index %= r.size();
  435. auto itr = std::begin(r);
  436. std::advance(itr, index);
  437. return *itr;
  438. }
  439. template<typename Range, typename Predicate>
  440. void erase_if(Range &vec, Predicate pred)
  441. {
  442. vec.erase(boost::remove_if(vec, pred),vec.end());
  443. }
  444. template<typename Elem, typename Predicate>
  445. void erase_if(std::set<Elem> &setContainer, Predicate pred)
  446. {
  447. auto itr = setContainer.begin();
  448. auto endItr = setContainer.end();
  449. while(itr != endItr)
  450. {
  451. auto tmpItr = itr++;
  452. if(pred(*tmpItr))
  453. setContainer.erase(tmpItr);
  454. }
  455. }
  456. //works for map and bmap, maybe something else
  457. template<typename Key, typename Val, typename Predicate>
  458. void erase_if(std::map<Key, Val> &container, Predicate pred)
  459. {
  460. auto itr = container.begin();
  461. auto endItr = container.end();
  462. while(itr != endItr)
  463. {
  464. auto tmpItr = itr++;
  465. if(pred(*tmpItr))
  466. container.erase(tmpItr);
  467. }
  468. }
  469. template<typename InputRange, typename OutputIterator, typename Predicate>
  470. OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
  471. {
  472. return std::copy_if(boost::const_begin(input), std::end(input), result, pred);
  473. }
  474. template <typename Container>
  475. std::insert_iterator<Container> set_inserter(Container &c)
  476. {
  477. return std::inserter(c, c.end());
  478. }
  479. //Returns iterator to the element for which the value of ValueFunction is minimal
  480. template<class ForwardRange, class ValueFunction>
  481. auto minElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  482. {
  483. typedef decltype(*std::begin(rng)) ElemType;
  484. return boost::min_element(rng, [&] (ElemType lhs, ElemType rhs) -> bool
  485. {
  486. return vf(lhs) < vf(rhs);
  487. });
  488. }
  489. //Returns iterator to the element for which the value of ValueFunction is maximal
  490. template<class ForwardRange, class ValueFunction>
  491. auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  492. {
  493. typedef decltype(*std::begin(rng)) ElemType;
  494. return boost::max_element(rng, [&] (ElemType lhs, ElemType rhs) -> bool
  495. {
  496. return vf(lhs) < vf(rhs);
  497. });
  498. }
  499. static inline int retreiveRandNum(const std::function<int()> &randGen)
  500. {
  501. if (randGen)
  502. return randGen();
  503. else
  504. return rand();
  505. }
  506. template <typename T> const T & pickRandomElementOf(const std::vector<T> &v, const std::function<int()> &randGen)
  507. {
  508. return v.at(retreiveRandNum(randGen) % v.size());
  509. }
  510. template<typename T>
  511. void advance(T &obj, int change)
  512. {
  513. obj = (T)(((int)obj) + change);
  514. }
  515. template <typename Container>
  516. 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)
  517. {
  518. if(c.size())
  519. return c.back();
  520. else
  521. return typename Container::value_type();
  522. }
  523. template <typename Container>
  524. 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)
  525. {
  526. if(c.size())
  527. return c.front();
  528. else
  529. return nullptr;
  530. }
  531. template <typename Container, typename Index>
  532. bool isValidIndex(const Container &c, Index i)
  533. {
  534. return i >= 0 && i < c.size();
  535. }
  536. template <typename Container, typename Index>
  537. boost::optional<typename Container::const_reference> tryAt(const Container &c, Index i)
  538. {
  539. if(isValidIndex(c, i))
  540. {
  541. auto itr = c.begin();
  542. std::advance(itr, i);
  543. return *itr;
  544. }
  545. return boost::none;
  546. }
  547. template <typename Container, typename Pred>
  548. static boost::optional<typename Container::const_reference> tryFindIf(const Container &r, const Pred &t)
  549. {
  550. auto pos = range::find_if(r, t);
  551. if(pos == boost::end(r))
  552. return boost::none;
  553. else
  554. return *pos;
  555. }
  556. template <typename Container>
  557. typename Container::const_reference atOrDefault(const Container &r, size_t index, const typename Container::const_reference &defaultValue)
  558. {
  559. if(index < r.size())
  560. return r[index];
  561. return defaultValue;
  562. }
  563. using boost::math::round;
  564. }
  565. using vstd::operator-=;
  566. using vstd::make_unique;
  567. /* ---------------------------------------------------------------------------- */
  568. /* VCMI headers */
  569. /* ---------------------------------------------------------------------------- */
  570. #include "lib/logging/CLogger.h"