Connection.h 33 KB

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