Global.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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. /* ---------------------------------------------------------------------------- */
  17. /* System detection. */
  18. /* ---------------------------------------------------------------------------- */
  19. // Based on: http://sourceforge.net/p/predef/wiki/OperatingSystems/
  20. // and on: http://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor
  21. // TODO?: Should be moved to vstd\os_detect.h (and then included by Global.h)
  22. #ifdef _WIN16 // Defined for 16-bit environments
  23. # error "16-bit Windows isn't supported"
  24. #elif defined(_WIN64) // Defined for 64-bit environments
  25. # define VCMI_WINDOWS
  26. # define VCMI_WINDOWS_64
  27. #elif defined(_WIN32) // Defined for both 32-bit and 64-bit environments
  28. # define VCMI_WINDOWS
  29. # define VCMI_WINDOWS_32
  30. #elif defined(_WIN32_WCE)
  31. # error "Windows CE isn't supported"
  32. #elif defined(__linux__) || defined(__gnu_linux__) || defined(linux) || defined(__linux)
  33. # define VCMI_UNIX
  34. # define VCMI_XDG
  35. # if defined(__ANDROID__) || defined(ANDROID)
  36. # define VCMI_ANDROID
  37. # endif
  38. #elif defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
  39. # define VCMI_UNIX
  40. # define VCMI_XDG
  41. # define VCMI_FREEBSD
  42. #elif defined(__OpenBSD__)
  43. # define VCMI_UNIX
  44. # define VCMI_XDG
  45. # define VCMI_OPENBSD
  46. #elif defined(__HAIKU__)
  47. # define VCMI_UNIX
  48. # define VCMI_XDG
  49. # define VCMI_HAIKU
  50. #elif defined(__GNU__) || defined(__gnu_hurd__) || (defined(__MACH__) && !defined(__APPLE__))
  51. # define VCMI_UNIX
  52. # define VCMI_XDG
  53. # define VCMI_HURD
  54. #elif defined(__APPLE__) && defined(__MACH__)
  55. # define VCMI_UNIX
  56. # define VCMI_APPLE
  57. # include "TargetConditionals.h"
  58. # if TARGET_OS_SIMULATOR || TARGET_IPHONE_SIMULATOR
  59. # define VCMI_IOS
  60. # define VCMI_IOS_SIM
  61. # elif TARGET_OS_IPHONE
  62. # define VCMI_IOS
  63. # elif TARGET_OS_MAC
  64. # define VCMI_MAC
  65. # else
  66. //# warning "Unknown Apple target."?
  67. # endif
  68. #else
  69. # error "This platform isn't supported"
  70. #endif
  71. #if defined(VCMI_ANDROID) || defined(VCMI_IOS)
  72. #define VCMI_MOBILE
  73. #endif
  74. /* ---------------------------------------------------------------------------- */
  75. /* Commonly used C++, Boost headers */
  76. /* ---------------------------------------------------------------------------- */
  77. #ifdef VCMI_WINDOWS
  78. # ifndef WIN32_LEAN_AND_MEAN
  79. # define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - delete this line if something is missing.
  80. # endif
  81. # ifndef NOMINMAX
  82. # define NOMINMAX // Exclude min/max macros from <Windows.h>. Use std::[min/max] from <algorithm> instead.
  83. # endif
  84. # ifndef _NO_W32_PSEUDO_MODIFIERS
  85. # define _NO_W32_PSEUDO_MODIFIERS // Exclude more macros for compiling with MinGW on Linux.
  86. # endif
  87. #endif
  88. /* ---------------------------------------------------------------------------- */
  89. /* A macro to force inlining some of our functions */
  90. /* ---------------------------------------------------------------------------- */
  91. // Compiler (at least MSVC) is not so smart here-> without that displaying is MUCH slower
  92. #ifdef _MSC_VER
  93. # define STRONG_INLINE __forceinline
  94. #elif __GNUC__
  95. # define STRONG_INLINE inline __attribute__((always_inline))
  96. #else
  97. # define STRONG_INLINE inline
  98. #endif
  99. // Required for building boost::stacktrace on macOS.
  100. // See https://github.com/boostorg/stacktrace/issues/88
  101. #if defined(VCMI_APPLE)
  102. #define _GNU_SOURCE
  103. #endif
  104. #define _USE_MATH_DEFINES
  105. #include <algorithm>
  106. #include <any>
  107. #include <array>
  108. #include <atomic>
  109. #include <bitset>
  110. #include <cassert>
  111. #include <chrono>
  112. #include <climits>
  113. #include <cmath>
  114. #include <codecvt>
  115. #include <cstdio>
  116. #include <cstdlib>
  117. #include <fstream>
  118. #include <functional>
  119. #include <iomanip>
  120. #include <iostream>
  121. #include <map>
  122. #include <memory>
  123. #include <mutex>
  124. #include <numeric>
  125. #include <optional>
  126. #include <queue>
  127. #include <random>
  128. #include <regex>
  129. #include <set>
  130. #include <shared_mutex>
  131. #include <sstream>
  132. #include <string>
  133. #include <unordered_map>
  134. #include <unordered_set>
  135. #include <utility>
  136. #include <variant>
  137. #include <vector>
  138. //The only available version is 3, as of Boost 1.50
  139. #include <boost/version.hpp>
  140. #define BOOST_FILESYSTEM_VERSION 3
  141. #if BOOST_VERSION > 105000
  142. # define BOOST_THREAD_VERSION 3
  143. #endif
  144. #if BOOST_VERSION == 107400
  145. # define BOOST_ALLOW_DEPRECATED_HEADERS
  146. #endif
  147. #define BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE 1
  148. //need to link boost thread dynamically to avoid https://stackoverflow.com/questions/35978572/boost-thread-interupt-does-not-work-when-crossing-a-dll-boundary
  149. //for example VCAI::finish() may freeze on thread join after interrupt when linking this statically
  150. #ifndef BOOST_THREAD_USE_DLL
  151. # define BOOST_THREAD_USE_DLL
  152. #endif
  153. #define BOOST_BIND_NO_PLACEHOLDERS
  154. #if BOOST_VERSION >= 106600
  155. #define BOOST_ASIO_ENABLE_OLD_SERVICES
  156. #endif
  157. #include <boost/algorithm/hex.hpp>
  158. #include <boost/algorithm/string.hpp>
  159. #include <boost/crc.hpp>
  160. #include <boost/current_function.hpp>
  161. #include <boost/container/small_vector.hpp>
  162. #include <boost/container/static_vector.hpp>
  163. #include <boost/date_time/posix_time/posix_time_types.hpp>
  164. #include <boost/date_time/posix_time/time_formatters.hpp>
  165. #include <boost/filesystem.hpp>
  166. #include <boost/filesystem/fstream.hpp>
  167. #include <boost/filesystem/path.hpp>
  168. #include <boost/format.hpp>
  169. #include <boost/functional/hash.hpp>
  170. #include <boost/lexical_cast.hpp>
  171. #ifdef VCMI_WINDOWS
  172. #include <boost/locale/generator.hpp>
  173. #endif
  174. #include <boost/logic/tribool.hpp>
  175. #include <boost/multi_array.hpp>
  176. #include <boost/range/adaptor/filtered.hpp>
  177. #include <boost/range/adaptor/reversed.hpp>
  178. #include <boost/range/algorithm.hpp>
  179. #include <boost/thread/thread_only.hpp>
  180. #include <boost/thread/shared_mutex.hpp>
  181. #include <boost/thread/recursive_mutex.hpp>
  182. #include <boost/thread/once.hpp>
  183. #ifndef M_PI
  184. # define M_PI 3.14159265358979323846
  185. #endif
  186. /* ---------------------------------------------------------------------------- */
  187. /* Usings */
  188. /* ---------------------------------------------------------------------------- */
  189. using namespace std::placeholders;
  190. namespace range = boost::range;
  191. /* ---------------------------------------------------------------------------- */
  192. /* Typedefs */
  193. /* ---------------------------------------------------------------------------- */
  194. // Integral data types
  195. typedef uint64_t ui64; //unsigned int 64 bits (8 bytes)
  196. typedef uint32_t ui32; //unsigned int 32 bits (4 bytes)
  197. typedef uint16_t ui16; //unsigned int 16 bits (2 bytes)
  198. typedef uint8_t ui8; //unsigned int 8 bits (1 byte)
  199. typedef int64_t si64; //signed int 64 bits (8 bytes)
  200. typedef int32_t si32; //signed int 32 bits (4 bytes)
  201. typedef int16_t si16; //signed int 16 bits (2 bytes)
  202. typedef int8_t si8; //signed int 8 bits (1 byte)
  203. // Lock typedefs
  204. using TLockGuard = std::lock_guard<std::mutex>;
  205. using TLockGuardRec = std::lock_guard<std::recursive_mutex>;
  206. /* ---------------------------------------------------------------------------- */
  207. /* Macros */
  208. /* ---------------------------------------------------------------------------- */
  209. // Import + Export macro declarations
  210. #ifdef VCMI_WINDOWS
  211. # ifdef VCMI_DLL_STATIC
  212. # define DLL_IMPORT
  213. # define DLL_EXPORT
  214. # elif defined(__GNUC__)
  215. # define DLL_IMPORT __attribute__((dllimport))
  216. # define DLL_EXPORT __attribute__((dllexport))
  217. # else
  218. # define DLL_IMPORT __declspec(dllimport)
  219. # define DLL_EXPORT __declspec(dllexport)
  220. # endif
  221. # define ELF_VISIBILITY
  222. #else
  223. # ifdef __GNUC__
  224. # define DLL_IMPORT __attribute__ ((visibility("default")))
  225. # define DLL_EXPORT __attribute__ ((visibility("default")))
  226. # define ELF_VISIBILITY __attribute__ ((visibility("default")))
  227. # endif
  228. #endif
  229. #ifdef VCMI_DLL
  230. # define DLL_LINKAGE DLL_EXPORT
  231. #else
  232. # define DLL_LINKAGE DLL_IMPORT
  233. #endif
  234. #define THROW_FORMAT(message, formatting_elems) throw std::runtime_error(boost::str(boost::format(message) % formatting_elems))
  235. // old iOS SDKs compatibility
  236. #ifdef VCMI_IOS
  237. #include <AvailabilityVersions.h>
  238. #ifndef __IPHONE_13_0
  239. #define __IPHONE_13_0 130000
  240. #endif
  241. #endif // VCMI_IOS
  242. // single-process build makes 2 copies of the main lib by wrapping it in a namespace
  243. #ifdef VCMI_LIB_NAMESPACE
  244. #define VCMI_LIB_NAMESPACE_BEGIN namespace VCMI_LIB_NAMESPACE {
  245. #define VCMI_LIB_NAMESPACE_END }
  246. #define VCMI_LIB_USING_NAMESPACE using namespace VCMI_LIB_NAMESPACE;
  247. #define VCMI_LIB_WRAP_NAMESPACE(x) VCMI_LIB_NAMESPACE::x
  248. #else
  249. #define VCMI_LIB_NAMESPACE_BEGIN
  250. #define VCMI_LIB_NAMESPACE_END
  251. #define VCMI_LIB_USING_NAMESPACE
  252. #define VCMI_LIB_WRAP_NAMESPACE(x) ::x
  253. #endif
  254. /* ---------------------------------------------------------------------------- */
  255. /* VCMI standard library */
  256. /* ---------------------------------------------------------------------------- */
  257. #include <vstd/CLoggerBase.h>
  258. VCMI_LIB_NAMESPACE_BEGIN
  259. namespace vstd
  260. {
  261. // combine hashes. Present in boost but not in std
  262. template <class T>
  263. inline void hash_combine(std::size_t& seed, const T& v)
  264. {
  265. std::hash<T> hasher;
  266. seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
  267. }
  268. //returns true if container c contains item i
  269. template <typename Container, typename Item>
  270. bool contains(const Container & c, const Item &i)
  271. {
  272. return std::find(std::begin(c), std::end(c),i) != std::end(c);
  273. }
  274. //returns true if container c contains item i
  275. template <typename Container, typename Pred>
  276. bool contains_if(const Container & c, Pred p)
  277. {
  278. return std::find_if(std::begin(c), std::end(c), p) != std::end(c);
  279. }
  280. //returns true if map c contains item i
  281. template <typename V, typename Item, typename Item2>
  282. bool contains(const std::map<Item,V> & c, const Item2 &i)
  283. {
  284. return c.find(i)!=c.end();
  285. }
  286. //returns true if unordered set c contains item i
  287. template <typename Item>
  288. bool contains(const std::unordered_set<Item> & c, const Item &i)
  289. {
  290. return c.find(i)!=c.end();
  291. }
  292. template <typename V, typename Item, typename Item2>
  293. bool contains(const std::unordered_map<Item,V> & c, const Item2 &i)
  294. {
  295. return c.find(i)!=c.end();
  296. }
  297. //returns position of first element in vector c equal to s, if there is no such element, -1 is returned
  298. template <typename Container, typename T2>
  299. int find_pos(const Container & c, const T2 &s)
  300. {
  301. int i=0;
  302. for (auto iter = std::begin(c); iter != std::end(c); iter++, i++)
  303. if(*iter == s)
  304. return i;
  305. return -1;
  306. }
  307. //Func f tells if element matches
  308. template <typename Container, typename Func>
  309. int find_pos_if(const Container & c, const Func &f)
  310. {
  311. auto ret = boost::range::find_if(c, f);
  312. if(ret != std::end(c))
  313. return std::distance(std::begin(c), ret);
  314. return -1;
  315. }
  316. //returns iterator to the given element if present in container, end() if not
  317. template <typename Container, typename Item>
  318. typename Container::iterator find(Container & c, const Item &i)
  319. {
  320. return std::find(c.begin(),c.end(),i);
  321. }
  322. //returns const iterator to the given element if present in container, end() if not
  323. template <typename Container, typename Item>
  324. typename Container::const_iterator find(const Container & c, const Item &i)
  325. {
  326. return std::find(c.begin(),c.end(),i);
  327. }
  328. // returns existing value from map, or default value if key does not exists
  329. template <typename Map>
  330. const typename Map::mapped_type & find_or(const Map& m, const typename Map::key_type& key, const typename Map::mapped_type& defaultValue) {
  331. auto it = m.find(key);
  332. if (it == m.end())
  333. return defaultValue;
  334. return it->second;
  335. }
  336. // given a map from keys to values, creates a new map from values to keys
  337. template<typename K, typename V>
  338. static std::map<V, K> reverseMap(const std::map<K, V>& m) {
  339. std::map<V, K> r;
  340. for (const auto& kv : m)
  341. r[kv.second] = kv.first;
  342. return r;
  343. }
  344. //returns first key that maps to given value if present, returns success via found if provided
  345. template <typename Key, typename T>
  346. Key findKey(const std::map<Key, T> & map, const T & value, bool * found = nullptr)
  347. {
  348. for(auto iter = map.cbegin(); iter != map.cend(); iter++)
  349. {
  350. if(iter->second == value)
  351. {
  352. if(found)
  353. *found = true;
  354. return iter->first;
  355. }
  356. }
  357. if(found)
  358. *found = false;
  359. return Key();
  360. }
  361. //removes element i from container c, returns false if c does not contain i
  362. template <typename Container, typename Item>
  363. typename Container::size_type operator-=(Container &c, const Item &i)
  364. {
  365. typename Container::iterator itr = find(c,i);
  366. if(itr == c.end())
  367. return false;
  368. c.erase(itr);
  369. return true;
  370. }
  371. //assigns greater of (a, b) to a and returns maximum of (a, b)
  372. template <typename t1, typename t2>
  373. t1 &amax(t1 &a, const t2 &b)
  374. {
  375. if(a >= (t1)b)
  376. return a;
  377. else
  378. {
  379. a = t1(b);
  380. return a;
  381. }
  382. }
  383. //assigns smaller of (a, b) to a and returns minimum of (a, b)
  384. template <typename t1, typename t2>
  385. t1 &amin(t1 &a, const t2 &b)
  386. {
  387. if(a <= (t1)b)
  388. return a;
  389. else
  390. {
  391. a = t1(b);
  392. return a;
  393. }
  394. }
  395. //makes a to fit the range <b, c>
  396. template <typename T>
  397. void abetween(T &value, const T &min, const T &max)
  398. {
  399. value = std::clamp(value, min, max);
  400. }
  401. //checks if a is between b and c
  402. template <typename t1, typename t2, typename t3>
  403. bool isbetween(const t1 &value, const t2 &min, const t3 &max)
  404. {
  405. return value > (t1)min && value < (t1)max;
  406. }
  407. //checks if a is within b and c
  408. template <typename t1, typename t2, typename t3>
  409. bool iswithin(const t1 &value, const t2 &min, const t3 &max)
  410. {
  411. return value >= (t1)min && value <= (t1)max;
  412. }
  413. template <typename t1, typename t2>
  414. struct assigner
  415. {
  416. public:
  417. t1 &op1;
  418. t2 op2;
  419. assigner(t1 &a1, const t2 & a2)
  420. :op1(a1), op2(a2)
  421. {}
  422. void operator()()
  423. {
  424. op1 = op2;
  425. }
  426. };
  427. //deleted pointer and sets it to nullptr
  428. template <typename T>
  429. void clear_pointer(T* &ptr)
  430. {
  431. delete ptr;
  432. ptr = nullptr;
  433. }
  434. template <typename Container>
  435. typename Container::const_reference circularAt(const Container &r, size_t index)
  436. {
  437. assert(r.size());
  438. index %= r.size();
  439. auto itr = std::begin(r);
  440. std::advance(itr, index);
  441. return *itr;
  442. }
  443. template <typename Container, typename Item>
  444. void erase(Container &c, const Item &item)
  445. {
  446. c.erase(boost::remove(c, item), c.end());
  447. }
  448. template<typename Range, typename Predicate>
  449. void erase_if(Range &vec, Predicate pred)
  450. {
  451. vec.erase(boost::remove_if(vec, pred),vec.end());
  452. }
  453. template<typename Elem, typename Predicate>
  454. void erase_if(std::set<Elem> &setContainer, Predicate pred)
  455. {
  456. auto itr = setContainer.begin();
  457. auto endItr = setContainer.end();
  458. while(itr != endItr)
  459. {
  460. auto tmpItr = itr++;
  461. if(pred(*tmpItr))
  462. setContainer.erase(tmpItr);
  463. }
  464. }
  465. template<typename Elem, typename Predicate>
  466. void erase_if(std::unordered_set<Elem> &setContainer, Predicate pred)
  467. {
  468. auto itr = setContainer.begin();
  469. auto endItr = setContainer.end();
  470. while(itr != endItr)
  471. {
  472. auto tmpItr = itr++;
  473. if(pred(*tmpItr))
  474. setContainer.erase(tmpItr);
  475. }
  476. }
  477. //works for map and std::map, maybe something else
  478. template<typename Key, typename Val, typename Predicate>
  479. void erase_if(std::map<Key, Val> &container, Predicate pred)
  480. {
  481. auto itr = container.begin();
  482. auto endItr = container.end();
  483. while(itr != endItr)
  484. {
  485. auto tmpItr = itr++;
  486. if(pred(*tmpItr))
  487. container.erase(tmpItr);
  488. }
  489. }
  490. //works for std::unordered_map, maybe something else
  491. template<typename Key, typename Val, typename Predicate>
  492. void erase_if(std::unordered_map<Key, Val> & container, Predicate pred)
  493. {
  494. auto itr = container.begin();
  495. auto endItr = container.end();
  496. while(itr != endItr)
  497. {
  498. auto tmpItr = itr++;
  499. if(pred(*tmpItr))
  500. container.erase(tmpItr);
  501. }
  502. }
  503. // Removes all duplicate elements from the vector
  504. template<typename T>
  505. void unique(std::vector<T> &vec)
  506. {
  507. std::sort(vec.begin(), vec.end());
  508. auto newEnd = std::unique(vec.begin(), vec.end());
  509. vec.erase(newEnd, vec.end());
  510. }
  511. template<typename InputRange, typename OutputIterator, typename Predicate>
  512. OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
  513. {
  514. return std::copy_if(std::cbegin(input), std::end(input), result, pred);
  515. }
  516. template <typename Container>
  517. std::insert_iterator<Container> set_inserter(Container &c)
  518. {
  519. return std::inserter(c, c.end());
  520. }
  521. //Returns iterator to the element for which the value of ValueFunction is minimal
  522. template<class ForwardRange, class ValueFunction>
  523. auto minElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  524. {
  525. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  526. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  527. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  528. * directly for both function parameters.
  529. */
  530. return boost::min_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  531. {
  532. return vf(lhs) < vf(rhs);
  533. });
  534. }
  535. //Returns iterator to the element for which the value of ValueFunction is maximal
  536. template<class ForwardRange, class ValueFunction>
  537. auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  538. {
  539. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  540. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  541. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  542. * directly for both function parameters.
  543. */
  544. return boost::max_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  545. {
  546. return vf(lhs) < vf(rhs);
  547. });
  548. }
  549. /// Increments value by specific delta
  550. /// similar to std::next but works with other types, e.g. enum class
  551. template<typename T>
  552. T next(const T &obj, int change)
  553. {
  554. return static_cast<T>(static_cast<ptrdiff_t>(obj) + change);
  555. }
  556. template <typename Container>
  557. 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)
  558. {
  559. if(c.size())
  560. return c.back();
  561. else
  562. return typename Container::value_type();
  563. }
  564. template <typename Container>
  565. 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)
  566. {
  567. if(c.size())
  568. return c.front();
  569. else
  570. return nullptr;
  571. }
  572. template <typename Container, typename Index>
  573. bool isValidIndex(const Container &c, Index i)
  574. {
  575. return i >= 0 && i < c.size();
  576. }
  577. template <typename Container>
  578. typename Container::const_reference atOrDefault(const Container &r, size_t index, const typename Container::const_reference &defaultValue)
  579. {
  580. if(index < r.size())
  581. return r[index];
  582. return defaultValue;
  583. }
  584. template <typename Container, typename Item>
  585. bool erase_if_present(Container &c, const Item &item)
  586. {
  587. auto i = std::find(c.begin(), c.end(), item);
  588. if (i != c.end())
  589. {
  590. c.erase(i);
  591. return true;
  592. }
  593. return false;
  594. }
  595. template <typename V, typename Item, typename Item2>
  596. bool erase_if_present(std::map<Item,V> & c, const Item2 &item)
  597. {
  598. auto i = c.find(item);
  599. if (i != c.end())
  600. {
  601. c.erase(i);
  602. return true;
  603. }
  604. return false;
  605. }
  606. template <typename Container>
  607. void removeDuplicates(Container &vec)
  608. {
  609. std::sort(vec.begin(), vec.end());
  610. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  611. }
  612. template <typename Container>
  613. void concatenate(Container &dest, const Container &src)
  614. {
  615. dest.reserve(dest.size() + src.size());
  616. dest.insert(dest.end(), src.begin(), src.end());
  617. }
  618. template <typename T>
  619. std::vector<T> intersection(std::vector<T> &v1, std::vector<T> &v2)
  620. {
  621. std::vector<T> v3;
  622. std::sort(v1.begin(), v1.end());
  623. std::sort(v2.begin(), v2.end());
  624. std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));
  625. return v3;
  626. }
  627. template <typename T>
  628. std::set<T> difference(const std::set<T> &s1, const std::set<T> s2)
  629. {
  630. std::set<T> s3;
  631. std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), std::inserter(s3, s3.end()));
  632. return s3;
  633. }
  634. template <typename Key, typename V>
  635. bool containsMapping(const std::multimap<Key,V> & map, const std::pair<const Key,V> & mapping)
  636. {
  637. auto range = map.equal_range(mapping.first);
  638. for(auto contained = range.first; contained != range.second; contained++)
  639. {
  640. if(mapping.second == contained->second)
  641. return true;
  642. }
  643. return false;
  644. }
  645. //c++20 feature
  646. template<typename Arithmetic, typename Floating>
  647. Arithmetic lerp(const Arithmetic & a, const Arithmetic & b, const Floating & f)
  648. {
  649. return a + (b - a) * f;
  650. }
  651. /// Divides dividend by divisor and rounds result up
  652. /// For use with integer-only arithmetic
  653. template<typename Integer1, typename Integer2>
  654. Integer1 divideAndCeil(const Integer1 & dividend, const Integer2 & divisor)
  655. {
  656. static_assert(std::is_integral_v<Integer1> && std::is_integral_v<Integer2>, "This function should only be used with integral types");
  657. return (dividend + divisor - 1) / divisor;
  658. }
  659. /// Divides dividend by divisor and rounds result to nearest
  660. /// For use with integer-only arithmetic
  661. template<typename Integer1, typename Integer2>
  662. Integer1 divideAndRound(const Integer1 & dividend, const Integer2 & divisor)
  663. {
  664. static_assert(std::is_integral_v<Integer1> && std::is_integral_v<Integer2>, "This function should only be used with integral types");
  665. return (dividend + divisor / 2 - 1) / divisor;
  666. }
  667. /// Divides dividend by divisor and rounds result down
  668. /// For use with integer-only arithmetic
  669. template<typename Integer1, typename Integer2>
  670. Integer1 divideAndFloor(const Integer1 & dividend, const Integer2 & divisor)
  671. {
  672. static_assert(std::is_integral_v<Integer1> && std::is_integral_v<Integer2>, "This function should only be used with integral types");
  673. return dividend / divisor;
  674. }
  675. template<typename Floating>
  676. bool isAlmostZero(const Floating & value)
  677. {
  678. constexpr Floating epsilon(0.00001);
  679. return std::abs(value) <= epsilon;
  680. }
  681. template<typename Floating1, typename Floating2>
  682. bool isAlmostEqual(const Floating1 & left, const Floating2 & right)
  683. {
  684. using Floating = decltype(left + right);
  685. constexpr Floating epsilon(0.00001);
  686. const Floating relativeEpsilon = std::max(std::abs(left), std::abs(right)) * epsilon;
  687. const Floating value = std::abs(left - right);
  688. return value <= relativeEpsilon;
  689. }
  690. ///compile-time version of std::abs for ints for int3, in clang++15 std::abs is constexpr
  691. static constexpr int abs(int i) {
  692. if(i < 0) return -i;
  693. return i;
  694. }
  695. ///C++23
  696. template< class Enum > constexpr std::underlying_type_t<Enum> to_underlying( Enum e ) noexcept
  697. {
  698. return static_cast<std::underlying_type_t<Enum>>(e);
  699. }
  700. }
  701. using vstd::operator-=;
  702. VCMI_LIB_NAMESPACE_END