Global.h 21 KB

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