Global.h 18 KB

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