BinaryDeserializer.h 14 KB

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