2
0

Connection.h 26 KB

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