Global.h 21 KB

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