BinaryDeserializer.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /*
  2. * BinaryDeserializer.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. #include <boost/mpl/vector.hpp>
  12. #include <boost/mpl/for_each.hpp>
  13. #include "CTypeList.h"
  14. #include "../mapObjects/CGHeroInstance.h"
  15. #include "../../Global.h"
  16. VCMI_LIB_NAMESPACE_BEGIN
  17. class CStackInstance;
  18. class DLL_LINKAGE CLoaderBase
  19. {
  20. protected:
  21. IBinaryReader * reader;
  22. public:
  23. CLoaderBase(IBinaryReader * r): reader(r){};
  24. inline int read(void * data, unsigned size)
  25. {
  26. return reader->read(data, size);
  27. };
  28. };
  29. /// Main class for deserialization of classes from binary form
  30. /// Effectively revesed version of BinarySerializer
  31. class DLL_LINKAGE BinaryDeserializer : public CLoaderBase
  32. {
  33. template<typename Variant, typename Source>
  34. struct VariantLoaderHelper
  35. {
  36. Source & source;
  37. std::vector<std::function<Variant()>> funcs;
  38. template <class V>
  39. struct mpl_types_impl;
  40. template <class... Ts>
  41. struct mpl_types_impl<std::variant<Ts...>> {
  42. using type = boost::mpl::vector<Ts...>;
  43. };
  44. template <class V>
  45. using mpl_types = typename mpl_types_impl<V>::type;
  46. VariantLoaderHelper(Source & source):
  47. source(source)
  48. {
  49. boost::mpl::for_each<mpl_types<Variant>>(std::ref(*this));
  50. }
  51. template<typename Type>
  52. void operator()(Type)
  53. {
  54. funcs.push_back([&]() -> Variant
  55. {
  56. Type obj;
  57. source.load(obj);
  58. return Variant(obj);
  59. });
  60. }
  61. };
  62. template<typename Ser,typename T>
  63. struct LoadIfStackInstance
  64. {
  65. static bool invoke(Ser &s, T &data)
  66. {
  67. return false;
  68. }
  69. };
  70. template<typename Ser>
  71. struct LoadIfStackInstance<Ser, CStackInstance *>
  72. {
  73. static bool invoke(Ser &s, CStackInstance* &data)
  74. {
  75. CArmedInstance *armedObj;
  76. SlotID slot;
  77. s.load(armedObj);
  78. s.load(slot);
  79. if(slot != SlotID::COMMANDER_SLOT_PLACEHOLDER)
  80. {
  81. assert(armedObj->hasStackAtSlot(slot));
  82. data = armedObj->stacks[slot];
  83. }
  84. else
  85. {
  86. auto * hero = dynamic_cast<CGHeroInstance *>(armedObj);
  87. assert(hero);
  88. assert(hero->commander);
  89. data = hero->commander;
  90. }
  91. return true;
  92. }
  93. };
  94. template <typename T, typename Enable = void>
  95. struct ClassObjectCreator
  96. {
  97. static T *invoke()
  98. {
  99. static_assert(!std::is_abstract<T>::value, "Cannot call new upon abstract classes!");
  100. return new T();
  101. }
  102. };
  103. template<typename T>
  104. struct ClassObjectCreator<T, typename std::enable_if<std::is_abstract<T>::value>::type>
  105. {
  106. static T *invoke()
  107. {
  108. throw std::runtime_error("Something went really wrong during deserialization. Attempted creating an object of an abstract class " + std::string(typeid(T).name()));
  109. }
  110. };
  111. STRONG_INLINE ui32 readAndCheckLength()
  112. {
  113. ui32 length;
  114. load(length);
  115. //NOTE: also used for h3m's embedded in campaigns, so it may be quite large in some cases (e.g. XXL maps with multiple objects)
  116. if(length > 1000000)
  117. {
  118. logGlobal->warn("Warning: very big length: %d", length);
  119. reader->reportState(logGlobal);
  120. };
  121. return length;
  122. }
  123. template <typename T> class CPointerLoader;
  124. class CBasicPointerLoader
  125. {
  126. public:
  127. virtual const std::type_info * loadPtr(CLoaderBase &ar, void *data, ui32 pid) const =0; //data is pointer to the ACTUAL POINTER
  128. virtual ~CBasicPointerLoader(){}
  129. template<typename T> static CBasicPointerLoader *getApplier(const T * t=nullptr)
  130. {
  131. return new CPointerLoader<T>();
  132. }
  133. };
  134. template <typename T> class CPointerLoader : public CBasicPointerLoader
  135. {
  136. public:
  137. const std::type_info * loadPtr(CLoaderBase &ar, void *data, ui32 pid) const override //data is pointer to the ACTUAL POINTER
  138. {
  139. auto & s = static_cast<BinaryDeserializer &>(ar);
  140. T *&ptr = *static_cast<T**>(data);
  141. //create new object under pointer
  142. typedef typename std::remove_pointer<T>::type npT;
  143. ptr = ClassObjectCreator<npT>::invoke(); //does new npT or throws for abstract classes
  144. s.ptrAllocated(ptr, pid);
  145. //T is most derived known type, it's time to call actual serialize
  146. assert(s.fileVersion != 0);
  147. ptr->serialize(s,s.fileVersion);
  148. return &typeid(T);
  149. }
  150. };
  151. CApplier<CBasicPointerLoader> applier;
  152. int write(const void * data, unsigned size);
  153. public:
  154. bool reverseEndianess; //if source has different endianness than us, we reverse bytes
  155. si32 fileVersion;
  156. std::map<ui32, void*> loadedPointers;
  157. std::map<ui32, const std::type_info*> loadedPointersTypes;
  158. std::map<const void*, std::any> loadedSharedPointers;
  159. bool smartPointerSerialization;
  160. bool saving;
  161. BinaryDeserializer(IBinaryReader * r): CLoaderBase(r)
  162. {
  163. saving = false;
  164. fileVersion = 0;
  165. smartPointerSerialization = true;
  166. reverseEndianess = false;
  167. }
  168. template<class T>
  169. BinaryDeserializer & operator&(T & t)
  170. {
  171. this->load(t);
  172. return * this;
  173. }
  174. template < class T, typename std::enable_if < std::is_fundamental<T>::value && !std::is_same<T, bool>::value, int >::type = 0 >
  175. void load(T &data)
  176. {
  177. unsigned length = sizeof(data);
  178. char * dataPtr = reinterpret_cast<char *>(&data);
  179. this->read(dataPtr,length);
  180. if(reverseEndianess)
  181. std::reverse(dataPtr, dataPtr + length);
  182. }
  183. template < typename T, typename std::enable_if < is_serializeable<BinaryDeserializer, T>::value, int >::type = 0 >
  184. void load(T &data)
  185. {
  186. assert( fileVersion != 0 );
  187. ////that const cast is evil because it allows to implicitly overwrite const objects when deserializing
  188. typedef typename std::remove_const<T>::type nonConstT;
  189. auto & hlp = const_cast<nonConstT &>(data);
  190. hlp.serialize(*this,fileVersion);
  191. }
  192. template < typename T, typename std::enable_if < std::is_array<T>::value, int >::type = 0 >
  193. void load(T &data)
  194. {
  195. ui32 size = std::size(data);
  196. for(ui32 i = 0; i < size; i++)
  197. load(data[i]);
  198. }
  199. template < typename T, typename std::enable_if < std::is_enum<T>::value, int >::type = 0 >
  200. void load(T &data)
  201. {
  202. si32 read;
  203. load( read );
  204. data = static_cast<T>(read);
  205. }
  206. template < typename T, typename std::enable_if < std::is_same<T, bool>::value, int >::type = 0 >
  207. void load(T &data)
  208. {
  209. ui8 read;
  210. load( read );
  211. data = static_cast<bool>(read);
  212. }
  213. template < typename T, typename std::enable_if < std::is_same<T, std::vector<bool> >::value, int >::type = 0 >
  214. void load(T & data)
  215. {
  216. std::vector<ui8> convData;
  217. load(convData);
  218. convData.resize(data.size());
  219. range::copy(convData, data.begin());
  220. }
  221. template <typename T, typename std::enable_if < !std::is_same<T, bool >::value, int >::type = 0>
  222. void load(std::vector<T> &data)
  223. {
  224. ui32 length = readAndCheckLength();
  225. data.resize(length);
  226. for(ui32 i=0;i<length;i++)
  227. load( data[i]);
  228. }
  229. template < typename T, typename std::enable_if < std::is_pointer<T>::value, int >::type = 0 >
  230. void load(T &data)
  231. {
  232. ui8 hlp;
  233. load( hlp );
  234. if(!hlp)
  235. {
  236. data = nullptr;
  237. return;
  238. }
  239. if(reader->smartVectorMembersSerialization)
  240. {
  241. typedef typename std::remove_const<typename std::remove_pointer<T>::type>::type TObjectType; //eg: const CGHeroInstance * => CGHeroInstance
  242. typedef typename VectorizedTypeFor<TObjectType>::type VType; //eg: CGHeroInstance -> CGobjectInstance
  243. typedef typename VectorizedIDType<TObjectType>::type IDType;
  244. if(const auto *info = reader->getVectorizedTypeInfo<VType, IDType>())
  245. {
  246. IDType id;
  247. load(id);
  248. if(id != IDType(-1))
  249. {
  250. data = static_cast<T>(reader->getVectorItemFromId<VType, IDType>(*info, id));
  251. return;
  252. }
  253. }
  254. }
  255. if(reader->sendStackInstanceByIds)
  256. {
  257. bool gotLoaded = LoadIfStackInstance<BinaryDeserializer,T>::invoke(* this, data);
  258. if(gotLoaded)
  259. return;
  260. }
  261. ui32 pid = 0xffffffff; //pointer id (or maybe rather pointee id)
  262. if(smartPointerSerialization)
  263. {
  264. load( pid ); //get the id
  265. auto i = loadedPointers.find(pid); //lookup
  266. if(i != loadedPointers.end())
  267. {
  268. // We already got this pointer
  269. // Cast it in case we are loading it to a non-first base pointer
  270. assert(loadedPointersTypes.count(pid));
  271. data = reinterpret_cast<T>(typeList.castRaw(i->second, loadedPointersTypes.at(pid), &typeid(typename std::remove_const<typename std::remove_pointer<T>::type>::type)));
  272. return;
  273. }
  274. }
  275. //get type id
  276. ui16 tid;
  277. load( tid );
  278. if(!tid)
  279. {
  280. typedef typename std::remove_pointer<T>::type npT;
  281. typedef typename std::remove_const<npT>::type ncpT;
  282. data = ClassObjectCreator<ncpT>::invoke();
  283. ptrAllocated(data, pid);
  284. load(*data);
  285. }
  286. else
  287. {
  288. auto * app = applier.getApplier(tid);
  289. if(app == nullptr)
  290. {
  291. logGlobal->error("load %d %d - no loader exists", tid, pid);
  292. data = nullptr;
  293. return;
  294. }
  295. auto typeInfo = app->loadPtr(*this,&data, pid);
  296. data = reinterpret_cast<T>(typeList.castRaw((void*)data, typeInfo, &typeid(typename std::remove_const<typename std::remove_pointer<T>::type>::type)));
  297. }
  298. }
  299. template <typename T>
  300. void ptrAllocated(const T *ptr, ui32 pid)
  301. {
  302. if(smartPointerSerialization && pid != 0xffffffff)
  303. {
  304. loadedPointersTypes[pid] = &typeid(T);
  305. loadedPointers[pid] = (void*)ptr; //add loaded pointer to our lookup map; cast is to avoid errors with const T* pt
  306. }
  307. }
  308. template<typename Base, typename Derived> void registerType(const Base * b = nullptr, const Derived * d = nullptr)
  309. {
  310. applier.registerType(b, d);
  311. }
  312. template <typename T>
  313. void load(std::shared_ptr<T> &data)
  314. {
  315. typedef typename std::remove_const<T>::type NonConstT;
  316. NonConstT *internalPtr;
  317. load(internalPtr);
  318. void *internalPtrDerived = typeList.castToMostDerived(internalPtr);
  319. if(internalPtr)
  320. {
  321. auto itr = loadedSharedPointers.find(internalPtrDerived);
  322. if(itr != loadedSharedPointers.end())
  323. {
  324. // This pointers is already loaded. The "data" needs to be pointed to it,
  325. // so their shared state is actually shared.
  326. try
  327. {
  328. auto actualType = typeList.getTypeInfo(internalPtr);
  329. auto typeWeNeedToReturn = typeList.getTypeInfo<T>();
  330. if(*actualType == *typeWeNeedToReturn)
  331. {
  332. // No casting needed, just unpack already stored shared_ptr and return it
  333. data = std::any_cast<std::shared_ptr<T>>(itr->second);
  334. }
  335. else
  336. {
  337. // We need to perform series of casts
  338. auto ret = typeList.castShared(itr->second, actualType, typeWeNeedToReturn);
  339. data = std::any_cast<std::shared_ptr<T>>(ret);
  340. }
  341. }
  342. catch(std::exception &e)
  343. {
  344. logGlobal->error(e.what());
  345. logGlobal->error("Failed to cast stored shared ptr. Real type: %s. Needed type %s. FIXME FIXME FIXME", itr->second.type().name(), typeid(std::shared_ptr<T>).name());
  346. //TODO scenario with inheritance -> we can have stored ptr to base and load ptr to derived (or vice versa)
  347. throw;
  348. }
  349. }
  350. else
  351. {
  352. auto hlp = std::shared_ptr<NonConstT>(internalPtr);
  353. data = hlp;
  354. loadedSharedPointers[internalPtrDerived] = typeList.castSharedToMostDerived(hlp);
  355. }
  356. }
  357. else
  358. data.reset();
  359. }
  360. template <typename T>
  361. void load(std::shared_ptr<const T> & data)
  362. {
  363. std::shared_ptr<T> nonConstData;
  364. load(nonConstData);
  365. data = nonConstData;
  366. }
  367. template <typename T>
  368. void load(std::unique_ptr<T> &data)
  369. {
  370. T *internalPtr;
  371. load( internalPtr );
  372. data.reset(internalPtr);
  373. }
  374. template <typename T, size_t N>
  375. void load(std::array<T, N> &data)
  376. {
  377. for(ui32 i = 0; i < N; i++)
  378. load( data[i] );
  379. }
  380. template <typename T>
  381. void load(std::set<T> &data)
  382. {
  383. ui32 length = readAndCheckLength();
  384. data.clear();
  385. T ins;
  386. for(ui32 i=0;i<length;i++)
  387. {
  388. load( ins );
  389. data.insert(ins);
  390. }
  391. }
  392. template <typename T, typename U>
  393. void load(std::unordered_set<T, U> &data)
  394. {
  395. ui32 length = readAndCheckLength();
  396. data.clear();
  397. T ins;
  398. for(ui32 i=0;i<length;i++)
  399. {
  400. load(ins);
  401. data.insert(ins);
  402. }
  403. }
  404. template <typename T>
  405. void load(std::list<T> &data)
  406. {
  407. ui32 length = readAndCheckLength();
  408. data.clear();
  409. T ins;
  410. for(ui32 i=0;i<length;i++)
  411. {
  412. load(ins);
  413. data.push_back(ins);
  414. }
  415. }
  416. template <typename T1, typename T2>
  417. void load(std::pair<T1,T2> &data)
  418. {
  419. load(data.first);
  420. load(data.second);
  421. }
  422. template <typename T1, typename T2>
  423. void load(std::map<T1,T2> &data)
  424. {
  425. ui32 length = readAndCheckLength();
  426. data.clear();
  427. T1 key;
  428. T2 value;
  429. for(ui32 i=0;i<length;i++)
  430. {
  431. load(key);
  432. load(value);
  433. data.insert(std::pair<T1, T2>(std::move(key), std::move(value)));
  434. }
  435. }
  436. template <typename T1, typename T2>
  437. void load(std::multimap<T1, T2> &data)
  438. {
  439. ui32 length = readAndCheckLength();
  440. data.clear();
  441. T1 key;
  442. T2 value;
  443. for(ui32 i = 0; i < length; i++)
  444. {
  445. load(key);
  446. load(value);
  447. data.insert(std::pair<T1, T2>(std::move(key), std::move(value)));
  448. }
  449. }
  450. void load(std::string &data)
  451. {
  452. ui32 length = readAndCheckLength();
  453. data.resize(length);
  454. this->read((void*)data.c_str(),length);
  455. }
  456. template<typename T0, typename... TN>
  457. void load(std::variant<T0, TN...> & data)
  458. {
  459. using TVariant = std::variant<T0, TN...>;
  460. VariantLoaderHelper<TVariant, BinaryDeserializer> loader(*this);
  461. si32 which;
  462. load( which );
  463. assert(which < loader.funcs.size());
  464. data = loader.funcs.at(which)();
  465. }
  466. template<typename T>
  467. void load(std::optional<T> & data)
  468. {
  469. ui8 present;
  470. load( present );
  471. if(present)
  472. {
  473. //TODO: replace with emplace once we start request Boost 1.56+, see PR360
  474. T t;
  475. load(t);
  476. data = std::make_optional(std::move(t));
  477. }
  478. else
  479. {
  480. data = std::optional<T>();
  481. }
  482. }
  483. template <typename T>
  484. void load(boost::multi_array<T, 3> & data)
  485. {
  486. ui32 length = readAndCheckLength();
  487. ui32 x, y, z;
  488. load(x);
  489. load(y);
  490. load(z);
  491. data.resize(boost::extents[x][y][z]);
  492. assert(length == data.num_elements()); //x*y*z should be equal to number of elements
  493. for(ui32 i = 0; i < length; i++)
  494. load(data.data()[i]);
  495. }
  496. template <std::size_t T>
  497. void load(std::bitset<T> &data)
  498. {
  499. static_assert(T <= 64);
  500. if constexpr (T <= 16)
  501. {
  502. uint16_t read;
  503. load(read);
  504. data = read;
  505. }
  506. else if constexpr (T <= 32)
  507. {
  508. uint32_t read;
  509. load(read);
  510. data = read;
  511. }
  512. else if constexpr (T <= 64)
  513. {
  514. uint64_t read;
  515. load(read);
  516. data = read;
  517. }
  518. }
  519. };
  520. class DLL_LINKAGE CLoadFile : public IBinaryReader
  521. {
  522. public:
  523. BinaryDeserializer serializer;
  524. std::string fName;
  525. std::unique_ptr<std::fstream> sfile;
  526. CLoadFile(const boost::filesystem::path & fname, int minimalVersion = SERIALIZATION_VERSION); //throws!
  527. virtual ~CLoadFile();
  528. int read(void * data, unsigned size) override; //throws!
  529. void openNextFile(const boost::filesystem::path & fname, int minimalVersion); //throws!
  530. void clear();
  531. void reportState(vstd::CLoggerBase * out) override;
  532. void checkMagicBytes(const std::string & text);
  533. template<class T>
  534. CLoadFile & operator>>(T &t)
  535. {
  536. serializer & t;
  537. return * this;
  538. }
  539. };
  540. VCMI_LIB_NAMESPACE_END