2
0

Global.h 23 KB

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