Global.h 21 KB

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