Connection.h 34 KB

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