Global.h 22 KB

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