Connection.h 26 KB

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