BinaryDeserializer.h 14 KB

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