BinaryDeserializer.h 12 KB

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