2
0

BinaryDeserializer.h 14 KB

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