BinaryDeserializer.h 14 KB

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