Connection.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  1. /*
  2. * Connection.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 <typeinfo> //XXX this is in namespace std if you want w/o use typeinfo.h?
  12. #include <boost/type_traits/is_fundamental.hpp>
  13. #include <boost/type_traits/is_enum.hpp>
  14. #include <boost/type_traits/is_pointer.hpp>
  15. #include <boost/type_traits/is_class.hpp>
  16. #include <boost/type_traits/is_base_of.hpp>
  17. #include <boost/type_traits/is_array.hpp>
  18. #include <boost/type_traits/remove_pointer.hpp>
  19. #include <boost/type_traits/remove_const.hpp>
  20. #include <boost/variant.hpp>
  21. #include <boost/mpl/eval_if.hpp>
  22. #include <boost/mpl/equal_to.hpp>
  23. #include <boost/mpl/int.hpp>
  24. #include <boost/mpl/identity.hpp>
  25. #include <boost/any.hpp>
  26. #include "ConstTransitivePtr.h"
  27. #include "CCreatureSet.h" //for CStackInstance
  28. #include "CObjectHandler.h" //for CArmedInstance
  29. #include "Mapping/CCampaignHandler.h" //for CCampaignState
  30. const ui32 version = 737;
  31. const TSlot COMMANDER_SLOT_PLACEHOLDER = -2;
  32. class CConnection;
  33. class CGObjectInstance;
  34. class CStackInstance;
  35. class CGameState;
  36. class CCreature;
  37. class LibClasses;
  38. class CHero;
  39. struct CPack;
  40. extern DLL_LINKAGE LibClasses * VLC;
  41. namespace mpl = boost::mpl;
  42. namespace boost
  43. {
  44. namespace asio
  45. {
  46. namespace ip
  47. {
  48. class tcp;
  49. }
  50. class io_service;
  51. template <typename Protocol> class stream_socket_service;
  52. template <typename Protocol,typename StreamSocketService>
  53. class basic_stream_socket;
  54. template <typename Protocol> class socket_acceptor_service;
  55. template <typename Protocol,typename SocketAcceptorService>
  56. class basic_socket_acceptor;
  57. }
  58. class mutex;
  59. }
  60. enum SerializationLvl
  61. {
  62. Wrong=0,
  63. Boolean,
  64. Primitive,
  65. Array,
  66. Pointer,
  67. Enum,
  68. Serializable,
  69. BooleanVector
  70. };
  71. struct TypeComparer
  72. {
  73. bool operator()(const std::type_info *a, const std::type_info *b) const
  74. {
  75. return a->before(*b);
  76. }
  77. };
  78. class DLL_LINKAGE CTypeList
  79. {
  80. typedef std::multimap<const std::type_info *,ui16,TypeComparer> TTypeMap;
  81. TTypeMap types;
  82. public:
  83. CTypeList();
  84. ui16 registerType(const std::type_info *type);
  85. template <typename T> ui16 registerType(const T * t = NULL)
  86. {
  87. return registerType(getTypeInfo(t));
  88. }
  89. ui16 getTypeID(const std::type_info *type);
  90. template <typename T> ui16 getTypeID(const T * t = NULL)
  91. {
  92. return getTypeID(getTypeInfo(t));
  93. }
  94. template <typename T> const std::type_info * getTypeInfo(const T * t = NULL)
  95. {
  96. if(t)
  97. return &typeid(*t);
  98. else
  99. return &typeid(T);
  100. }
  101. };
  102. extern DLL_LINKAGE CTypeList typeList;
  103. template<typename Ser>
  104. struct SaveBoolean
  105. {
  106. static void invoke(Ser &s, const bool &data)
  107. {
  108. s.saveBoolean(data);
  109. }
  110. };
  111. template<typename Ser>
  112. struct LoadBoolean
  113. {
  114. static void invoke(Ser &s, bool &data)
  115. {
  116. s.loadBoolean(data);
  117. }
  118. };
  119. template<typename Ser>
  120. struct SaveBooleanVector
  121. {
  122. static void invoke(Ser &s, const std::vector<bool> &data)
  123. {
  124. s.saveBooleanVector(data);
  125. }
  126. };
  127. template<typename Ser>
  128. struct LoadBooleanVector
  129. {
  130. static void invoke(Ser &s, std::vector<bool> &data)
  131. {
  132. s.loadBooleanVector(data);
  133. }
  134. };
  135. template<typename Ser,typename T>
  136. struct SavePrimitive
  137. {
  138. static void invoke(Ser &s, const T &data)
  139. {
  140. s.savePrimitive(data);
  141. }
  142. };
  143. template<typename Ser,typename T>
  144. struct SaveSerializable
  145. {
  146. static void invoke(Ser &s, const T &data)
  147. {
  148. s.saveSerializable(data);
  149. }
  150. };
  151. template<typename Ser,typename T>
  152. struct SaveEnum
  153. {
  154. static void invoke(Ser &s, const T &data)
  155. {
  156. s.saveEnum(data);
  157. }
  158. };
  159. template<typename Ser,typename T>
  160. struct LoadEnum
  161. {
  162. static void invoke(Ser &s, T &data)
  163. {
  164. s.loadEnum(data);
  165. }
  166. };
  167. template<typename Ser,typename T>
  168. struct LoadPrimitive
  169. {
  170. static void invoke(Ser &s, T &data)
  171. {
  172. s.loadPrimitive(data);
  173. }
  174. };
  175. template<typename Ser,typename T>
  176. struct SavePointer
  177. {
  178. static void invoke(Ser &s, const T &data)
  179. {
  180. s.savePointer(data);
  181. }
  182. };
  183. template<typename Ser,typename T>
  184. struct LoadPointer
  185. {
  186. static void invoke(Ser &s, T &data)
  187. {
  188. s.loadPointer(data);
  189. }
  190. };
  191. template<typename Ser,typename T>
  192. struct SaveArray
  193. {
  194. static void invoke(Ser &s, const T &data)
  195. {
  196. s.saveArray(data);
  197. }
  198. };
  199. template<typename Ser,typename T>
  200. struct LoadArray
  201. {
  202. static void invoke(Ser &s, T &data)
  203. {
  204. s.loadArray(data);
  205. }
  206. };
  207. template<typename Ser,typename T>
  208. struct LoadSerializable
  209. {
  210. static void invoke(Ser &s, T &data)
  211. {
  212. s.loadSerializable(data);
  213. }
  214. };
  215. template<typename Ser,typename T>
  216. struct SaveWrong
  217. {
  218. static void invoke(Ser &s, const T &data)
  219. {
  220. throw std::runtime_error("Wrong save serialization call!");
  221. }
  222. };
  223. template<typename Ser,typename T>
  224. struct LoadWrong
  225. {
  226. static void invoke(Ser &s, const T &data)
  227. {
  228. throw std::runtime_error("Wrong load serialization call!");
  229. }
  230. };
  231. template<typename T>
  232. struct SerializationLevel
  233. {
  234. typedef mpl::integral_c_tag tag;
  235. typedef
  236. typename mpl::eval_if<
  237. boost::is_same<T, bool>,
  238. mpl::int_<Boolean>,
  239. //else
  240. typename mpl::eval_if<
  241. boost::is_same<T, std::vector<bool> >,
  242. mpl::int_<BooleanVector>,
  243. //else
  244. typename mpl::eval_if<
  245. boost::is_fundamental<T>,
  246. mpl::int_<Primitive>,
  247. //else
  248. typename mpl::eval_if<
  249. boost::is_enum<T>,
  250. mpl::int_<Enum>,
  251. //else
  252. typename mpl::eval_if<
  253. boost::is_class<T>,
  254. mpl::int_<Serializable>,
  255. //else
  256. typename mpl::eval_if<
  257. boost::is_array<T>,
  258. mpl::int_<Array>,
  259. //else
  260. typename mpl::eval_if<
  261. boost::is_pointer<T>,
  262. mpl::int_<Pointer>,
  263. //else
  264. typename mpl::eval_if<
  265. boost::is_enum<T>,
  266. mpl::int_<Primitive>,
  267. //else
  268. mpl::int_<Wrong>
  269. >
  270. >
  271. >
  272. >
  273. >
  274. >
  275. >
  276. >::type type;
  277. static const int value = SerializationLevel::type::value;
  278. };
  279. template <typename T, typename U>
  280. struct VectorisedObjectInfo
  281. {
  282. const std::vector<ConstTransitivePtr<T> > *vector; //pointer to the appropriate vector
  283. const U T::*idPtr; //pointer to the field representing the position in the vector
  284. VectorisedObjectInfo(const std::vector< ConstTransitivePtr<T> > *Vector, const U T::*IdPtr)
  285. :vector(Vector), idPtr(IdPtr)
  286. {
  287. }
  288. };
  289. /// Class which is responsible for storing and loading data.
  290. class DLL_LINKAGE CSerializer
  291. {
  292. public:
  293. typedef std::map<const std::type_info *, boost::any, TypeComparer> TTypeVecMap;
  294. TTypeVecMap vectors; //entry must be a pointer to vector containing pointers to the objects of key type
  295. bool smartVectorMembersSerialization;
  296. bool sendStackInstanceByIds;
  297. CSerializer();
  298. ~CSerializer();
  299. virtual void reportState(CLogger &out){};
  300. template <typename T, typename U>
  301. void registerVectoredType(const std::vector<T*> *Vector, const U T::*IdPtr)
  302. {
  303. vectors[&typeid(T)] = VectorisedObjectInfo<T, U>(Vector, IdPtr);
  304. }
  305. template <typename T, typename U>
  306. void registerVectoredType(const std::vector<ConstTransitivePtr<T> > *Vector, const U T::*IdPtr)
  307. {
  308. vectors[&typeid(T)] = VectorisedObjectInfo<T, U>(Vector, IdPtr);
  309. }
  310. template <typename T, typename U>
  311. const VectorisedObjectInfo<T, U> *getVectorisedTypeInfo()
  312. {
  313. const std::type_info *myType = NULL;
  314. //
  315. // if(boost::is_base_of<CGObjectInstance, T>::value) //ugly workaround to support also types derived from CGObjectInstance -> if we encounter one, treat it aas CGObj..
  316. // myType = &typeid(CGObjectInstance);
  317. // else
  318. myType = &typeid(T);
  319. TTypeVecMap::iterator i = vectors.find(myType);
  320. if(i == vectors.end())
  321. return NULL;
  322. else
  323. {
  324. assert(!i->second.empty());
  325. assert(i->second.type() == typeid(VectorisedObjectInfo<T, U>));
  326. VectorisedObjectInfo<T, U> *ret = &(boost::any_cast<VectorisedObjectInfo<T, U>&>(i->second));
  327. return ret;
  328. }
  329. }
  330. template <typename T, typename U>
  331. T* getVectorItemFromId(const VectorisedObjectInfo<T, U> &oInfo, U id) const
  332. {
  333. /* if(id < 0)
  334. return NULL;*/
  335. assert(oInfo.vector);
  336. assert(oInfo.vector->size() > id);
  337. return const_cast<T*>((*oInfo.vector)[id].get());
  338. }
  339. template <typename T, typename U>
  340. U getIdFromVectorItem(const VectorisedObjectInfo<T, U> &oInfo, const T* obj) const
  341. {
  342. if(!obj)
  343. return U(-1);
  344. return obj->*oInfo.idPtr;
  345. }
  346. void addStdVecItems(CGameState *gs, LibClasses *lib = VLC);
  347. };
  348. class DLL_LINKAGE CSaverBase : public virtual CSerializer
  349. {
  350. };
  351. class CBasicPointerSaver
  352. {
  353. public:
  354. virtual void savePtr(CSaverBase &ar, const void *data) const =0;
  355. virtual ~CBasicPointerSaver(){}
  356. };
  357. template <typename Serializer, typename T> class CPointerSaver : public CBasicPointerSaver
  358. {
  359. public:
  360. void savePtr(CSaverBase &ar, const void *data) const
  361. {
  362. Serializer &s = static_cast<Serializer&>(ar);
  363. const T *ptr = static_cast<const T*>(data);
  364. //T is most derived known type, it's time to call actual serialize
  365. const_cast<T&>(*ptr).serialize(s,version);
  366. }
  367. };
  368. template <typename T> //metafunction returning CGObjectInstance if T is its derivate or T elsewise
  369. struct VectorisedTypeFor
  370. {
  371. typedef typename
  372. //if
  373. mpl::eval_if<boost::is_base_of<CGObjectInstance,T>,
  374. mpl::identity<CGObjectInstance>,
  375. //else
  376. mpl::identity<T>
  377. >::type type;
  378. };
  379. template <typename U>
  380. struct VectorizedIDType
  381. {
  382. typedef typename
  383. //if
  384. mpl::eval_if<boost::is_same<CArtifact,U>,
  385. mpl::identity<ArtifactID>,
  386. //else if
  387. mpl::eval_if<boost::is_same<CCreature,U>,
  388. mpl::identity<CreatureID>,
  389. //else
  390. mpl::identity<si32>
  391. >
  392. >::type type;
  393. };
  394. template <typename Handler>
  395. struct VariantVisitorSaver : boost::static_visitor<>
  396. {
  397. Handler &h;
  398. VariantVisitorSaver(Handler &H):h(H)
  399. {
  400. }
  401. template <typename T>
  402. void operator()(const T &t)
  403. {
  404. h << t;
  405. }
  406. };
  407. template<typename Ser,typename T>
  408. struct SaveIfStackInstance
  409. {
  410. static bool invoke(Ser &s, const T &data)
  411. {
  412. return false;
  413. }
  414. };
  415. template<typename Ser>
  416. struct SaveIfStackInstance<Ser, CStackInstance *>
  417. {
  418. static bool invoke(Ser &s, const CStackInstance* const &data)
  419. {
  420. assert(data->armyObj);
  421. TSlot slot = -1;
  422. if(data->getNodeType() == CBonusSystemNode::COMMANDER)
  423. slot = COMMANDER_SLOT_PLACEHOLDER;
  424. else
  425. slot = data->armyObj->findStack(data);
  426. assert(slot != -1);
  427. s << data->armyObj << slot;
  428. return true;
  429. }
  430. };
  431. template<typename Ser,typename T>
  432. struct LoadIfStackInstance
  433. {
  434. static bool invoke(Ser &s, T &data)
  435. {
  436. return false;
  437. }
  438. };
  439. template<typename Ser>
  440. struct LoadIfStackInstance<Ser, CStackInstance *>
  441. {
  442. static bool invoke(Ser &s, CStackInstance* &data)
  443. {
  444. CArmedInstance *armedObj;
  445. TSlot slot;
  446. s >> armedObj >> slot;
  447. if(slot != COMMANDER_SLOT_PLACEHOLDER)
  448. {
  449. assert(armedObj->hasStackAtSlot(slot));
  450. data = armedObj->stacks[slot];
  451. }
  452. else
  453. {
  454. auto hero = dynamic_cast<CGHeroInstance *>(armedObj);
  455. assert(hero);
  456. assert(hero->commander);
  457. data = hero->commander;
  458. }
  459. return true;
  460. }
  461. };
  462. /// The class which manages saving objects.
  463. template <typename Serializer> class DLL_LINKAGE COSer : public CSaverBase
  464. {
  465. public:
  466. bool saving;
  467. std::map<ui16,CBasicPointerSaver*> savers; // typeID => CPointerSaver<serializer,type>
  468. std::map<const void*, ui32> savedPointers;
  469. bool smartPointerSerialization;
  470. COSer()
  471. {
  472. saving=true;
  473. smartPointerSerialization = true;
  474. }
  475. ~COSer()
  476. {
  477. std::map<ui16,CBasicPointerSaver*>::iterator iter;
  478. for(iter = savers.begin(); iter != savers.end(); iter++)
  479. delete iter->second;
  480. }
  481. template<typename T> void registerType(const T * t=NULL)
  482. {
  483. ui16 ID = typeList.registerType(t);
  484. savers[ID] = new CPointerSaver<COSer<Serializer>,T>;
  485. }
  486. Serializer * This()
  487. {
  488. return static_cast<Serializer*>(this);
  489. }
  490. template<class T>
  491. Serializer & operator<<(const T &t)
  492. {
  493. this->This()->save(t);
  494. return * this->This();
  495. }
  496. template<class T>
  497. COSer & operator&(const T & t)
  498. {
  499. return * this->This() << t;
  500. }
  501. int write(const void * data, unsigned size);
  502. template <typename T>
  503. void savePrimitive(const T &data)
  504. {
  505. this->This()->write(&data,sizeof(data));
  506. }
  507. template <typename T>
  508. void savePointer(const T &data)
  509. {
  510. //write if pointer is not NULL
  511. ui8 hlp = (data!=NULL);
  512. *this << hlp;
  513. //if pointer is NULL then we don't need anything more...
  514. if(!hlp)
  515. return;
  516. if(smartVectorMembersSerialization)
  517. {
  518. typedef typename boost::remove_const<typename boost::remove_pointer<T>::type>::type TObjectType;
  519. typedef typename VectorisedTypeFor<TObjectType>::type VType;
  520. typedef typename VectorizedIDType<TObjectType>::type IDType;
  521. if(const auto *info = getVectorisedTypeInfo<VType, IDType>())
  522. {
  523. si32 id = getIdFromVectorItem<VType>(*info, data);
  524. *this << id;
  525. if(id != -1) //vector id is enough
  526. return;
  527. }
  528. }
  529. if(sendStackInstanceByIds)
  530. {
  531. const bool gotSaved = SaveIfStackInstance<Serializer,T>::invoke(*This(), data);
  532. if(gotSaved)
  533. return;
  534. }
  535. if(smartPointerSerialization)
  536. {
  537. std::map<const void*,ui32>::iterator i = savedPointers.find(data);
  538. if(i != savedPointers.end())
  539. {
  540. //this pointer has been already serialized - write only it's id
  541. *this << i->second;
  542. return;
  543. }
  544. //give id to this pointer
  545. ui32 pid = (ui32)savedPointers.size();
  546. savedPointers[data] = pid;
  547. *this << pid;
  548. }
  549. //write type identifier
  550. ui16 tid = typeList.getTypeID(data);
  551. *this << tid;
  552. This()->savePointerHlp(tid, data);
  553. }
  554. //that part of ptr serialization was extracted to allow customization of its behavior in derived classes
  555. template <typename T>
  556. void savePointerHlp(ui16 tid, const T &data)
  557. {
  558. if(!tid)
  559. *this << *data; //if type is unregistered simply write all data in a standard way
  560. else
  561. savers[tid]->savePtr(*this,data); //call serializer specific for our real type
  562. }
  563. template <typename T>
  564. void saveArray(const T &data)
  565. {
  566. ui32 size = ARRAY_COUNT(data);
  567. for(ui32 i=0; i < size; i++)
  568. *this << data[i];
  569. }
  570. template <typename T>
  571. void save(const T &data)
  572. {
  573. typedef
  574. //if
  575. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Boolean> >,
  576. mpl::identity<SaveBoolean<Serializer> >,
  577. //else if
  578. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<BooleanVector> >,
  579. mpl::identity<SaveBooleanVector<Serializer> >,
  580. //else if
  581. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Primitive> >,
  582. mpl::identity<SavePrimitive<Serializer,T> >,
  583. //else if
  584. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Enum> >,
  585. mpl::identity<SaveEnum<Serializer,T> >,
  586. //else if
  587. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Pointer> >,
  588. mpl::identity<SavePointer<Serializer,T> >,
  589. //else if
  590. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Array> >,
  591. mpl::identity<SaveArray<Serializer,T> >,
  592. //else if
  593. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Serializable> >,
  594. mpl::identity<SaveSerializable<Serializer,T> >,
  595. //else
  596. mpl::identity<SaveWrong<Serializer,T> >
  597. >
  598. >
  599. >
  600. >
  601. >
  602. >
  603. >::type typex;
  604. typex::invoke(* this->This(), data);
  605. }
  606. template <typename T>
  607. void saveSerializable(const T &data)
  608. {
  609. const_cast<T&>(data).serialize(*this,version);
  610. }
  611. template <typename T>
  612. void saveSerializable(const shared_ptr<T> &data)
  613. {
  614. T *internalPtr = data.get();
  615. *this << internalPtr;
  616. }
  617. template <typename T>
  618. void saveSerializable(const unique_ptr<T> &data)
  619. {
  620. T *internalPtr = data.get();
  621. *this << internalPtr;
  622. }
  623. template <typename T>
  624. void saveSerializable(const std::vector<T> &data)
  625. {
  626. ui32 length = data.size();
  627. *this << length;
  628. for(ui32 i=0;i<length;i++)
  629. *this << data[i];
  630. }
  631. template <typename T>
  632. void saveSerializable(const std::set<T> &data)
  633. {
  634. std::set<T> &d = const_cast<std::set<T> &>(data);
  635. ui32 length = d.size();
  636. *this << length;
  637. for(typename std::set<T>::iterator i=d.begin();i!=d.end();i++)
  638. *this << *i;
  639. }
  640. template <typename T, typename U>
  641. void saveSerializable(const boost::unordered_set<T, U> &data)
  642. {
  643. boost::unordered_set<T, U> &d = const_cast<boost::unordered_set<T, U> &>(data);
  644. ui32 length = d.size();
  645. *this << length;
  646. for(typename boost::unordered_set<T, U>::iterator i=d.begin();i!=d.end();i++)
  647. *this << *i;
  648. }
  649. template <typename T>
  650. void saveSerializable(const std::list<T> &data)
  651. {
  652. std::list<T> &d = const_cast<std::list<T> &>(data);
  653. ui32 length = d.size();
  654. *this << length;
  655. for(typename std::list<T>::iterator i=d.begin();i!=d.end();i++)
  656. *this << *i;
  657. }
  658. void saveSerializable(const std::string &data)
  659. {
  660. *this << ui32(data.length());
  661. this->This()->write(data.c_str(),data.size());
  662. }
  663. template <typename T1, typename T2>
  664. void saveSerializable(const std::pair<T1,T2> &data)
  665. {
  666. *this << data.first << data.second;
  667. }
  668. template <typename T1, typename T2>
  669. void saveSerializable(const std::map<T1,T2> &data)
  670. {
  671. *this << ui32(data.size());
  672. for(typename std::map<T1,T2>::const_iterator i=data.begin();i!=data.end();i++)
  673. *this << i->first << i->second;
  674. }
  675. template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
  676. void saveSerializable(const boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &data)
  677. {
  678. si32 which = data.which();
  679. *this << which;
  680. VariantVisitorSaver<Serializer> visitor(*this->This());
  681. boost::apply_visitor(visitor, data);
  682. }
  683. template <typename T>
  684. void saveSerializable(const boost::optional<T> &data)
  685. {
  686. if(data)
  687. {
  688. *this << (ui8)1;
  689. *this << *data;
  690. }
  691. else
  692. {
  693. *this << (ui8)0;
  694. }
  695. }
  696. template <typename E>
  697. void saveEnum(const E &data)
  698. {
  699. si32 writ = static_cast<si32>(data);
  700. *this << writ;
  701. }
  702. void saveBoolean(const bool & data)
  703. {
  704. ui8 writ = static_cast<ui8>(data);
  705. *this << writ;
  706. }
  707. void saveBooleanVector(const std::vector<bool> & data)
  708. {
  709. std::vector<ui8> convData;
  710. std::copy(data.begin(), data.end(), std::back_inserter(convData));
  711. saveSerializable(convData);
  712. }
  713. };
  714. class DLL_LINKAGE CLoaderBase : public virtual CSerializer
  715. {};
  716. class CBasicPointerLoader
  717. {
  718. public:
  719. virtual void loadPtr(CLoaderBase &ar, void *data, ui32 pid) const =0; //data is pointer to the ACTUAL POINTER
  720. virtual ~CBasicPointerLoader(){}
  721. };
  722. template <typename Serializer, typename T> class CPointerLoader : public CBasicPointerLoader
  723. {
  724. public:
  725. void loadPtr(CLoaderBase &ar, void *data, ui32 pid) const //data is pointer to the ACTUAL POINTER
  726. {
  727. Serializer &s = static_cast<Serializer&>(ar);
  728. T *&ptr = *static_cast<T**>(data);
  729. //create new object under pointer
  730. typedef typename boost::remove_pointer<T>::type npT;
  731. ptr = new npT;
  732. s.ptrAllocated(ptr, pid);
  733. //T is most derived known type, it's time to call actual serialize
  734. ptr->serialize(s,version);
  735. }
  736. };
  737. /// The class which manages loading of objects.
  738. template <typename Serializer> class DLL_LINKAGE CISer : public CLoaderBase
  739. {
  740. public:
  741. bool saving;
  742. std::map<ui16,CBasicPointerLoader*> loaders; // typeID => CPointerSaver<serializer,type>
  743. ui32 fileVersion;
  744. bool reverseEndianess; //if source has different endianess than us, we reverse bytes
  745. std::map<ui32, void*> loadedPointers;
  746. bool smartPointerSerialization;
  747. CISer()
  748. {
  749. saving = false;
  750. fileVersion = 0;
  751. smartPointerSerialization = true;
  752. reverseEndianess = false;
  753. }
  754. ~CISer()
  755. {
  756. std::map<ui16,CBasicPointerLoader*>::iterator iter;
  757. for(iter = loaders.begin(); iter != loaders.end(); iter++)
  758. delete iter->second;
  759. }
  760. template<typename T> void registerType(const T * t=NULL)
  761. {
  762. ui16 ID = typeList.registerType(t);
  763. loaders[ID] = new CPointerLoader<CISer<Serializer>,T>;
  764. }
  765. Serializer * This()
  766. {
  767. return static_cast<Serializer*>(this);
  768. }
  769. template<class T>
  770. Serializer & operator>>(T &t)
  771. {
  772. this->This()->load(t);
  773. return * this->This();
  774. }
  775. template<class T>
  776. CISer & operator&(T & t)
  777. {
  778. return * this->This() >> t;
  779. }
  780. int write(const void * data, unsigned size);
  781. template <typename T>
  782. void load(T &data)
  783. {
  784. typedef
  785. //if
  786. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Boolean> >,
  787. mpl::identity<LoadBoolean<Serializer> >,
  788. //else if
  789. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<BooleanVector> >,
  790. mpl::identity<LoadBooleanVector<Serializer> >,
  791. //else if
  792. typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Primitive> >,
  793. mpl::identity<LoadPrimitive<Serializer,T> >,
  794. //else if
  795. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Enum> >,
  796. mpl::identity<LoadEnum<Serializer,T> >,
  797. //else if
  798. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Pointer> >,
  799. mpl::identity<LoadPointer<Serializer,T> >,
  800. //else if
  801. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Array> >,
  802. mpl::identity<LoadArray<Serializer,T> >,
  803. //else if
  804. typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Serializable> >,
  805. mpl::identity<LoadSerializable<Serializer,T> >,
  806. //else
  807. mpl::identity<LoadWrong<Serializer,T> >
  808. >
  809. >
  810. >
  811. >
  812. >
  813. >
  814. >::type typex;
  815. typex::invoke(* this->This(), data);
  816. }
  817. template <typename T>
  818. void loadPrimitive(T &data)
  819. {
  820. if(0) //for testing #989
  821. {
  822. this->This()->read(&data,sizeof(data));
  823. }
  824. else
  825. {
  826. unsigned length = sizeof(data);
  827. char* dataPtr = (char*)&data;
  828. this->This()->read(dataPtr,length);
  829. if(reverseEndianess)
  830. std::reverse(dataPtr, dataPtr + length);
  831. }
  832. }
  833. template <typename T>
  834. void loadSerializableBySerializeCall(T &data)
  835. {
  836. ////that const cast is evil because it allows to implicitly overwrite const objects when deserializing
  837. typedef typename boost::remove_const<T>::type nonConstT;
  838. nonConstT &hlp = const_cast<nonConstT&>(data);
  839. hlp.serialize(*this,fileVersion);
  840. //data.serialize(*this,myVersion);
  841. }
  842. template <typename T>
  843. void loadSerializable(T &data)
  844. {
  845. loadSerializableBySerializeCall(data);
  846. }
  847. template <typename T>
  848. void loadArray(T &data)
  849. {
  850. ui32 size = ARRAY_COUNT(data);
  851. for(ui32 i = 0; i < size; i++)
  852. *this >> data[i];
  853. }
  854. template <typename T>
  855. void loadPointer(T &data)
  856. {
  857. ui8 hlp;
  858. *this >> hlp;
  859. if(!hlp)
  860. {
  861. data = NULL;
  862. return;
  863. }
  864. if(smartVectorMembersSerialization)
  865. {
  866. typedef typename boost::remove_const<typename boost::remove_pointer<T>::type>::type TObjectType; //eg: const CGHeroInstance * => CGHeroInstance
  867. typedef typename VectorisedTypeFor<TObjectType>::type VType; //eg: CGHeroInstance -> CGobjectInstance
  868. typedef typename VectorizedIDType<TObjectType>::type IDType;
  869. if(const auto *info = getVectorisedTypeInfo<VType, IDType>())
  870. {
  871. si32 id;
  872. *this >> id;
  873. if(id != -1)
  874. {
  875. data = static_cast<T>(getVectorItemFromId<VType, IDType>(*info, IDType(id)));
  876. return;
  877. }
  878. }
  879. }
  880. if(sendStackInstanceByIds)
  881. {
  882. bool gotLoaded = LoadIfStackInstance<Serializer,T>::invoke(*This(), data);
  883. if(gotLoaded)
  884. return;
  885. }
  886. ui32 pid = 0xffffffff; //pointer id (or maybe rather pointee id)
  887. if(smartPointerSerialization)
  888. {
  889. *this >> pid; //get the id
  890. std::map<ui32, void*>::iterator i = loadedPointers.find(pid); //lookup
  891. if(i != loadedPointers.end())
  892. {
  893. //we already got this pointer
  894. data = static_cast<T>(i->second);
  895. return;
  896. }
  897. }
  898. //get type id
  899. ui16 tid;
  900. *this >> tid;
  901. This()->loadPointerHlp(tid, data, pid);
  902. }
  903. //that part of ptr deserialization was extracted to allow customization of its behavior in derived classes
  904. template <typename T>
  905. void loadPointerHlp( ui16 tid, T & data, ui32 pid )
  906. {
  907. if(!tid)
  908. {
  909. typedef typename boost::remove_pointer<T>::type npT;
  910. typedef typename boost::remove_const<npT>::type ncpT;
  911. data = new ncpT;
  912. ptrAllocated(data, pid);
  913. *this >> *data;
  914. }
  915. else
  916. {
  917. loaders[tid]->loadPtr(*this,&data, pid);
  918. }
  919. }
  920. template <typename T>
  921. void ptrAllocated(const T *ptr, ui32 pid)
  922. {
  923. if(smartPointerSerialization && pid != 0xffffffff)
  924. loadedPointers[pid] = (void*)ptr; //add loaded pointer to our lookup map; cast is to avoid errors with const T* pt
  925. }
  926. #define READ_CHECK_U32(x) \
  927. ui32 length; \
  928. *this >> length; \
  929. if(length > 500000) \
  930. { \
  931. tlog2 << "Warning: very big length: " << length << "\n" ;\
  932. reportState(tlog2); \
  933. };
  934. template <typename T>
  935. void loadSerializable(shared_ptr<T> &data)
  936. {
  937. T *internalPtr;
  938. *this >> internalPtr;
  939. data.reset(internalPtr);
  940. }
  941. template <typename T>
  942. void loadSerializable(unique_ptr<T> &data)
  943. {
  944. T *internalPtr;
  945. *this >> internalPtr;
  946. data.reset(internalPtr);
  947. }
  948. template <typename T>
  949. void loadSerializable(std::vector<T> &data)
  950. {
  951. READ_CHECK_U32(length);
  952. data.resize(length);
  953. for(ui32 i=0;i<length;i++)
  954. *this >> data[i];
  955. }
  956. template <typename T>
  957. void loadSerializable(std::set<T> &data)
  958. {
  959. READ_CHECK_U32(length);
  960. T ins;
  961. for(ui32 i=0;i<length;i++)
  962. {
  963. *this >> ins;
  964. data.insert(ins);
  965. }
  966. }
  967. template <typename T, typename U>
  968. void loadSerializable(boost::unordered_set<T, U> &data)
  969. {
  970. READ_CHECK_U32(length);
  971. T ins;
  972. for(ui32 i=0;i<length;i++)
  973. {
  974. *this >> ins;
  975. data.insert(ins);
  976. }
  977. }
  978. template <typename T>
  979. void loadSerializable(std::list<T> &data)
  980. {
  981. READ_CHECK_U32(length);
  982. T ins;
  983. for(ui32 i=0;i<length;i++)
  984. {
  985. *this >> ins;
  986. data.push_back(ins);
  987. }
  988. }
  989. template <typename T1, typename T2>
  990. void loadSerializable(std::pair<T1,T2> &data)
  991. {
  992. *this >> data.first >> data.second;
  993. }
  994. template <typename T1, typename T2>
  995. void loadSerializable(std::map<T1,T2> &data)
  996. {
  997. READ_CHECK_U32(length);
  998. T1 t;
  999. for(ui32 i=0;i<length;i++)
  1000. {
  1001. *this >> t;
  1002. *this >> data[t];
  1003. }
  1004. }
  1005. void loadSerializable(std::string &data)
  1006. {
  1007. READ_CHECK_U32(length);
  1008. data.resize(length);
  1009. this->This()->read((void*)data.c_str(),length);
  1010. }
  1011. template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
  1012. void loadSerializable(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &data)
  1013. {
  1014. si32 which;
  1015. *this >> which;
  1016. if(which == 0)
  1017. {
  1018. T0 obj;
  1019. *this >> obj;
  1020. data = obj;
  1021. }
  1022. else if(which == 1)
  1023. {
  1024. T1 obj;
  1025. *this >> obj;
  1026. data = obj;
  1027. }
  1028. else
  1029. assert(0);
  1030. //TODO write more if needed, general solution would be much longer
  1031. }
  1032. template <typename T>
  1033. void loadSerializable(boost::optional<T> & data)
  1034. {
  1035. ui8 present;
  1036. *this >> present;
  1037. if(present)
  1038. {
  1039. T t;
  1040. *this >> t;
  1041. data = t;
  1042. }
  1043. else
  1044. {
  1045. data = boost::optional<T>();
  1046. }
  1047. }
  1048. void loadSerializable(CStackInstance *&s)
  1049. {
  1050. if(sendStackInstanceByIds)
  1051. {
  1052. CArmedInstance *armed;
  1053. TSlot slot;
  1054. *this >> armed >> slot;
  1055. assert(armed->hasStackAtSlot(slot));
  1056. s = armed->stacks[slot];
  1057. }
  1058. else
  1059. loadSerializableBySerializeCall(s);
  1060. }
  1061. template <typename E>
  1062. void loadEnum(E &data)
  1063. {
  1064. si32 read;
  1065. *this >> read;
  1066. data = static_cast<E>(read);
  1067. }
  1068. void loadBoolean(bool &data)
  1069. {
  1070. ui8 read;
  1071. *this >> read;
  1072. data = static_cast<bool>(read);
  1073. }
  1074. void loadBooleanVector(std::vector<bool> & data)
  1075. {
  1076. std::vector<ui8> convData;
  1077. loadSerializable(convData);
  1078. std::copy(convData.begin(), convData.end(), std::back_inserter(data));
  1079. }
  1080. };
  1081. class DLL_LINKAGE CSaveFile
  1082. : public COSer<CSaveFile>
  1083. {
  1084. void dummyMagicFunction()
  1085. {
  1086. *this << std::string("This function makes stuff working.");
  1087. }
  1088. public:
  1089. std::string fName;
  1090. unique_ptr<std::ofstream> sfile;
  1091. CSaveFile(const std::string &fname); //throws!
  1092. ~CSaveFile();
  1093. int write(const void * data, unsigned size);
  1094. void openNextFile(const std::string &fname); //throws!
  1095. void clear();
  1096. void reportState(CLogger &out);
  1097. };
  1098. class DLL_LINKAGE CLoadFile
  1099. : public CISer<CLoadFile>
  1100. {
  1101. void dummyMagicFunction()
  1102. {
  1103. std::string dummy = "This function makes stuff working.";
  1104. *this >> dummy;
  1105. }
  1106. public:
  1107. std::string fName;
  1108. unique_ptr<std::ifstream> sfile;
  1109. CLoadFile(const std::string &fname, int minimalVersion = version); //throws!
  1110. ~CLoadFile();
  1111. int read(const void * data, unsigned size); //throws!
  1112. void openNextFile(const std::string &fname, int minimalVersion); //throws!
  1113. void clear();
  1114. void reportState(CLogger &out);
  1115. };
  1116. typedef boost::asio::basic_stream_socket < boost::asio::ip::tcp , boost::asio::stream_socket_service<boost::asio::ip::tcp> > TSocket;
  1117. typedef boost::asio::basic_socket_acceptor<boost::asio::ip::tcp, boost::asio::socket_acceptor_service<boost::asio::ip::tcp> > TAcceptor;
  1118. class DLL_LINKAGE CConnection
  1119. :public CISer<CConnection>, public COSer<CConnection>
  1120. {
  1121. //CGameState *gs;
  1122. CConnection(void);
  1123. void init();
  1124. void reportState(CLogger &out);
  1125. public:
  1126. boost::mutex *rmx, *wmx; // read/write mutexes
  1127. TSocket * socket;
  1128. bool logging;
  1129. bool connected;
  1130. bool myEndianess, contactEndianess; //true if little endian, if endianess is different we'll have to revert received multi-byte vars
  1131. boost::asio::io_service *io_service;
  1132. std::string name; //who uses this connection
  1133. int connectionID;
  1134. boost::thread *handler;
  1135. bool receivedStop, sendStop;
  1136. CConnection(std::string host, std::string port, std::string Name);
  1137. CConnection(TAcceptor * acceptor, boost::asio::io_service *Io_service, std::string Name);
  1138. CConnection(TSocket * Socket, std::string Name); //use immediately after accepting connection into socket
  1139. int write(const void * data, unsigned size);
  1140. int read(void * data, unsigned size);
  1141. void close();
  1142. bool isOpen() const;
  1143. template<class T>
  1144. CConnection &operator&(const T&);
  1145. virtual ~CConnection(void);
  1146. CPack *retreivePack(); //gets from server next pack (allocates it with new)
  1147. void sendPackToServer(const CPack &pack, TPlayerColor player, ui32 requestID);
  1148. void disableStackSendingByID();
  1149. void enableStackSendingByID();
  1150. void disableSmartPointerSerialization();
  1151. void enableSmartPointerSerializatoin();
  1152. void prepareForSendingHeroes(); //disables sending vectorised, enables smart pointer serialization, clears saved/loaded ptr cache
  1153. };
  1154. DLL_LINKAGE std::ostream &operator<<(std::ostream &str, const CConnection &cpc);
  1155. template<typename T>
  1156. class CApplier
  1157. {
  1158. public:
  1159. std::map<ui16,T*> apps;
  1160. ~CApplier()
  1161. {
  1162. typename std::map<ui16, T*>::iterator iter;
  1163. for(iter = apps.begin(); iter != apps.end(); iter++)
  1164. delete iter->second;
  1165. }
  1166. template<typename U> void registerType(const U * t=NULL)
  1167. {
  1168. ui16 ID = typeList.registerType(t);
  1169. apps[ID] = T::getApplier(t);
  1170. }
  1171. };