Client.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. #include "StdInc.h"
  2. #include "Client.h"
  3. #include <SDL.h>
  4. #include "CMusicHandler.h"
  5. #include "../lib/mapping/CCampaignHandler.h"
  6. #include "../CCallback.h"
  7. #include "../lib/CConsoleHandler.h"
  8. #include "CGameInfo.h"
  9. #include "../lib/CGameState.h"
  10. #include "CPlayerInterface.h"
  11. #include "../lib/StartInfo.h"
  12. #include "../lib/BattleState.h"
  13. #include "../lib/CModHandler.h"
  14. #include "../lib/CArtHandler.h"
  15. #include "../lib/CGeneralTextHandler.h"
  16. #include "../lib/CHeroHandler.h"
  17. #include "../lib/CTownHandler.h"
  18. #include "../lib/CBuildingHandler.h"
  19. #include "../lib/CSpellHandler.h"
  20. #include "../lib/Connection.h"
  21. #ifndef VCMI_ANDROID
  22. #include "../lib/Interprocess.h"
  23. #endif
  24. #include "../lib/NetPacks.h"
  25. #include "../lib/VCMI_Lib.h"
  26. #include "../lib/VCMIDirs.h"
  27. #include "../lib/mapping/CMap.h"
  28. #include "../lib/JsonNode.h"
  29. #include "mapHandler.h"
  30. #include "../lib/CConfigHandler.h"
  31. #include "Client.h"
  32. #include "CPreGame.h"
  33. #include "battle/CBattleInterface.h"
  34. #include "../lib/CThreadHelper.h"
  35. #include "../lib/CScriptingModule.h"
  36. #include "../lib/registerTypes/RegisterTypes.h"
  37. #include "gui/CGuiHandler.h"
  38. #include "CMT.h"
  39. extern std::string NAME;
  40. #ifndef VCMI_ANDROID
  41. namespace intpr = boost::interprocess;
  42. #endif
  43. /*
  44. * Client.cpp, part of VCMI engine
  45. *
  46. * Authors: listed in file AUTHORS in main folder
  47. *
  48. * License: GNU General Public License v2.0 or later
  49. * Full text of license available in license.txt file, in main folder
  50. *
  51. */
  52. template <typename T> class CApplyOnCL;
  53. class CBaseForCLApply
  54. {
  55. public:
  56. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  57. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  58. virtual ~CBaseForCLApply(){}
  59. template<typename U> static CBaseForCLApply *getApplier(const U * t=nullptr)
  60. {
  61. return new CApplyOnCL<U>;
  62. }
  63. };
  64. template <typename T> class CApplyOnCL : public CBaseForCLApply
  65. {
  66. public:
  67. void applyOnClAfter(CClient *cl, void *pack) const
  68. {
  69. T *ptr = static_cast<T*>(pack);
  70. ptr->applyCl(cl);
  71. }
  72. void applyOnClBefore(CClient *cl, void *pack) const
  73. {
  74. T *ptr = static_cast<T*>(pack);
  75. ptr->applyFirstCl(cl);
  76. }
  77. };
  78. template <> class CApplyOnCL<CPack> : public CBaseForCLApply
  79. {
  80. public:
  81. void applyOnClAfter(CClient *cl, void *pack) const
  82. {
  83. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  84. assert(0);
  85. }
  86. void applyOnClBefore(CClient *cl, void *pack) const
  87. {
  88. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  89. assert(0);
  90. }
  91. };
  92. static CApplier<CBaseForCLApply> *applier = nullptr;
  93. void CClient::init()
  94. {
  95. hotSeat = false;
  96. connectionHandler = nullptr;
  97. pathInfo = nullptr;
  98. applier = new CApplier<CBaseForCLApply>;
  99. registerTypesClientPacks1(*applier);
  100. registerTypesClientPacks2(*applier);
  101. IObjectInterface::cb = this;
  102. serv = nullptr;
  103. gs = nullptr;
  104. erm = nullptr;
  105. terminate = false;
  106. }
  107. CClient::CClient(void)
  108. {
  109. init();
  110. }
  111. CClient::CClient(CConnection *con, StartInfo *si)
  112. {
  113. init();
  114. newGame(con,si);
  115. }
  116. CClient::~CClient(void)
  117. {
  118. delete applier;
  119. }
  120. void CClient::waitForMoveAndSend(PlayerColor color)
  121. {
  122. try
  123. {
  124. setThreadName("CClient::waitForMoveAndSend");
  125. assert(vstd::contains(battleints, color));
  126. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  127. logNetwork->traceStream() << "Send battle action to server: " << ba;
  128. MakeAction temp_action(ba);
  129. sendRequest(&temp_action, color);
  130. return;
  131. }
  132. catch(boost::thread_interrupted&)
  133. {
  134. logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
  135. return;
  136. }
  137. HANDLE_EXCEPTION
  138. logNetwork->errorStream() << "We should not be here!";
  139. }
  140. void CClient::run()
  141. {
  142. setThreadName("CClient::run");
  143. try
  144. {
  145. while(!terminate)
  146. {
  147. CPack *pack = serv->retreivePack(); //get the package from the server
  148. if (terminate)
  149. {
  150. vstd::clear_pointer(pack);
  151. break;
  152. }
  153. handlePack(pack);
  154. }
  155. }
  156. //catch only asio exceptions
  157. catch (const boost::system::system_error& e)
  158. {
  159. logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
  160. logNetwork->errorStream() << e.what();
  161. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  162. {
  163. logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
  164. throw;
  165. }
  166. }
  167. }
  168. void CClient::save(const std::string & fname)
  169. {
  170. if(gs->curB)
  171. {
  172. logNetwork->errorStream() << "Game cannot be saved during battle!";
  173. return;
  174. }
  175. SaveGame save_game(fname);
  176. sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
  177. }
  178. void CClient::endGame( bool closeConnection /*= true*/ )
  179. {
  180. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  181. for(auto i : playerint)
  182. i.second->finish();
  183. // Game is ending
  184. // Tell the network thread to reach a stable state
  185. if(closeConnection)
  186. stopConnection();
  187. logNetwork->infoStream() << "Closed connection.";
  188. GH.curInt = nullptr;
  189. {
  190. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  191. logNetwork->infoStream() << "Ending current game!";
  192. if(GH.topInt())
  193. GH.topInt()->deactivate();
  194. GH.listInt.clear();
  195. GH.objsToBlit.clear();
  196. GH.statusbar = nullptr;
  197. logNetwork->infoStream() << "Removed GUI.";
  198. vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
  199. vstd::clear_pointer(gs);
  200. logNetwork->infoStream() << "Deleted mapHandler and gameState.";
  201. LOCPLINT = nullptr;
  202. }
  203. playerint.clear();
  204. battleints.clear();
  205. callbacks.clear();
  206. battleCallbacks.clear();
  207. logNetwork->infoStream() << "Deleted playerInts.";
  208. logNetwork->infoStream() << "Client stopped.";
  209. }
  210. #if 0
  211. void CClient::loadGame(const std::string & fname, const bool server, const std::vector<int>& humanplayerindices, const int loadNumPlayers, int player_, const std::string & ipaddr, const std::string & port)
  212. {
  213. logNetwork->infoStream() <<"Loading procedure started!";
  214. CServerHandler sh;
  215. sh.startServer();
  216. CStopWatch tmh;
  217. try
  218. {
  219. std::string clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  220. std::string controlServerSaveName;
  221. if (CResourceHandler::get("local")->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
  222. {
  223. controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  224. }
  225. else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  226. {
  227. controlServerSaveName = clientSaveName.substr(0, clientSaveName.find_last_of(".")) + ".vsgm1";
  228. CResourceHandler::get("local")->createResource(controlServerSaveName, true);
  229. }
  230. if(clientSaveName.empty())
  231. throw std::runtime_error("Cannot open client part of " + fname);
  232. if(controlServerSaveName.empty())
  233. throw std::runtime_error("Cannot open server part of " + fname);
  234. unique_ptr<CLoadFile> loader;
  235. {
  236. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName, minSupportedVersion);
  237. loadCommonState(checkingLoader);
  238. loader = checkingLoader.decay();
  239. }
  240. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  241. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  242. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  243. pathInfo = make_unique<CPathsInfo>(getMapSize());
  244. CGI->mh->init();
  245. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  246. *loader >> *this;
  247. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  248. }
  249. catch(std::exception &e)
  250. {
  251. logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
  252. throw; //obviously we cannot continue here
  253. }
  254. serv = sh.connectToServer();
  255. serv->addStdVecItems(gs);
  256. tmh.update();
  257. ui8 pom8;
  258. *serv << ui8(3) << ui8(1); //load game; one client
  259. *serv << fname;
  260. *serv >> pom8;
  261. if(pom8)
  262. throw std::runtime_error("Server cannot open the savegame!");
  263. else
  264. logNetwork->infoStream() << "Server opened savegame properly.";
  265. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  266. for(auto & elem : gs->scenarioOps->playerInfos)
  267. {
  268. *serv << ui8(elem.first.getNum()); //players
  269. }
  270. *serv << ui8(PlayerColor::NEUTRAL.getNum());
  271. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  272. serv->enableStackSendingByID();
  273. serv->disableSmartPointerSerialization();
  274. // logGlobal->traceStream() << "Objects:";
  275. // for(int i = 0; i < gs->map->objects.size(); i++)
  276. // {
  277. // auto o = gs->map->objects[i];
  278. // if(o)
  279. // logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
  280. // else
  281. // logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
  282. // }
  283. }
  284. #endif
  285. #if 1
  286. void CClient::loadGame(const std::string & fname, const bool server, const std::vector<int>& humanplayerindices, const int loadNumPlayers, int player_, const std::string & ipaddr, const std::string & port)
  287. {
  288. PlayerColor player(player_); //intentional shadowing
  289. logNetwork->infoStream() <<"Loading procedure started!";
  290. CServerHandler sh;
  291. if(server)
  292. sh.startServer();
  293. else
  294. serv = sh.justConnectToServer(ipaddr,port=="" ? "3030" : port);
  295. CStopWatch tmh;
  296. unique_ptr<CLoadFile> loader;
  297. try
  298. {
  299. std::string clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  300. std::string controlServerSaveName;
  301. if (CResourceHandler::get("local")->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
  302. {
  303. controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  304. }
  305. else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  306. {
  307. controlServerSaveName = clientSaveName.substr(0, clientSaveName.find_last_of(".")) + ".vsgm1";
  308. CResourceHandler::get("local")->createResource(controlServerSaveName, true);
  309. }
  310. if(clientSaveName.empty())
  311. throw std::runtime_error("Cannot open client part of " + fname);
  312. if(controlServerSaveName.empty())
  313. throw std::runtime_error("Cannot open server part of " + fname);
  314. {
  315. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName, minSupportedVersion);
  316. loadCommonState(checkingLoader);
  317. loader = checkingLoader.decay();
  318. }
  319. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  320. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  321. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  322. pathInfo = make_unique<CPathsInfo>(getMapSize());
  323. CGI->mh->init();
  324. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  325. }
  326. catch(std::exception &e)
  327. {
  328. logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
  329. throw; //obviously we cannot continue here
  330. }
  331. /*
  332. if(!server)
  333. player = PlayerColor(player_);
  334. */
  335. std::set<PlayerColor> clientPlayers;
  336. if(server)
  337. serv = sh.connectToServer();
  338. //*loader >> *this;
  339. if(server)
  340. {
  341. tmh.update();
  342. ui8 pom8;
  343. *serv << ui8(3) << ui8(loadNumPlayers); //load game; one client if single-player
  344. *serv << fname;
  345. *serv >> pom8;
  346. if(pom8)
  347. throw std::runtime_error("Server cannot open the savegame!");
  348. else
  349. logNetwork->infoStream() << "Server opened savegame properly.";
  350. }
  351. player = PlayerColor(player_);
  352. if(server)
  353. {
  354. for(auto & elem : gs->scenarioOps->playerInfos)
  355. if(!std::count(humanplayerindices.begin(),humanplayerindices.end(),elem.first.getNum()) || elem.first==player)
  356. {
  357. clientPlayers.insert(elem.first);
  358. }
  359. clientPlayers.insert(PlayerColor::NEUTRAL);
  360. }
  361. else
  362. {
  363. clientPlayers.insert(player);
  364. }
  365. std::cout << "CLIENTPLAYERS:\n";
  366. for(auto x : clientPlayers)
  367. std::cout << x << std::endl;
  368. std::cout << "ENDCLIENTPLAYERS\n";
  369. serialize(*loader,0,clientPlayers);
  370. *serv << ui32(clientPlayers.size());
  371. for(auto & elem : clientPlayers)
  372. *serv << ui8(elem.getNum());
  373. serv->addStdVecItems(gs); /*why is this here?*/
  374. //*loader >> *this;
  375. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  376. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  377. //*serv << clientPlayers;
  378. serv->enableStackSendingByID();
  379. serv->disableSmartPointerSerialization();
  380. loadNeutralBattleAI(); //wtf did this come from
  381. // logGlobal->traceStream() << "Objects:";
  382. // for(int i = 0; i < gs->map->objects.size(); i++)
  383. // {
  384. // auto o = gs->map->objects[i];
  385. // if(o)
  386. // logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
  387. // else
  388. // logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
  389. // }
  390. }
  391. #endif
  392. void CClient::newGame( CConnection *con, StartInfo *si )
  393. {
  394. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  395. if (con == nullptr)
  396. {
  397. CServerHandler sh;
  398. serv = sh.connectToServer();
  399. }
  400. else
  401. {
  402. serv = con;
  403. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  404. }
  405. CConnection &c = *serv;
  406. ////////////////////////////////////////////////////
  407. logNetwork->infoStream() <<"\tWill send info to server...";
  408. CStopWatch tmh;
  409. if(networkMode == SINGLE)
  410. {
  411. ui8 pom8;
  412. c << ui8(2) << ui8(1); //new game; one client
  413. c << *si;
  414. c >> pom8;
  415. if(pom8) throw std::runtime_error("Server cannot open the map!");
  416. }
  417. c >> si;
  418. logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
  419. c.enableStackSendingByID();
  420. c.disableSmartPointerSerialization();
  421. // Initialize game state
  422. gs = new CGameState();
  423. logNetwork->infoStream() <<"\tCreating gamestate: "<<tmh.getDiff();
  424. gs->scenarioOps = si;
  425. gs->init(si);
  426. logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
  427. // Now after possible random map gen, we know exact player count.
  428. // Inform server about how many players client handles
  429. std::set<PlayerColor> myPlayers;
  430. for(auto & elem : gs->scenarioOps->playerInfos)
  431. {
  432. if((networkMode == SINGLE) //single - one client has all player
  433. || (networkMode != SINGLE && serv->connectionID == elem.second.playerID) //multi - client has only "its players"
  434. || (networkMode == HOST && elem.second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
  435. {
  436. myPlayers.insert(elem.first); //add player
  437. }
  438. }
  439. if(networkMode != GUEST)
  440. myPlayers.insert(PlayerColor::NEUTRAL);
  441. c << myPlayers;
  442. // Init map handler
  443. if(gs->map)
  444. {
  445. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  446. CGI->mh->map = gs->map;
  447. logNetwork->infoStream() <<"Creating mapHandler: "<<tmh.getDiff();
  448. CGI->mh->init();
  449. pathInfo = make_unique<CPathsInfo>(getMapSize());
  450. logNetwork->infoStream() <<"Initializing mapHandler (together): "<<tmh.getDiff();
  451. }
  452. int humanPlayers = 0;
  453. for(auto & elem : gs->scenarioOps->playerInfos)//initializing interfaces for players
  454. {
  455. PlayerColor color = elem.first;
  456. gs->currentPlayer = color;
  457. if(!vstd::contains(myPlayers, color))
  458. continue;
  459. logNetwork->traceStream() << "Preparing interface for player " << color;
  460. if(si->mode != StartInfo::DUEL)
  461. {
  462. if(elem.second.playerID == PlayerSettings::PLAYER_AI)
  463. {
  464. auto AiToGive = aiNameForPlayer(elem.second, false);
  465. logNetwork->infoStream() << boost::format("Player %s will be lead by %s") % color % AiToGive;
  466. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  467. }
  468. else
  469. {
  470. installNewPlayerInterface(make_shared<CPlayerInterface>(color), color);
  471. humanPlayers++;
  472. }
  473. }
  474. else
  475. {
  476. std::string AItoGive = aiNameForPlayer(elem.second, true);
  477. installNewBattleInterface(CDynLibHandler::getNewBattleAI(AItoGive), color);
  478. }
  479. }
  480. if(si->mode == StartInfo::DUEL)
  481. {
  482. if(!gNoGUI)
  483. {
  484. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  485. auto p = make_shared<CPlayerInterface>(PlayerColor::NEUTRAL);
  486. p->observerInDuelMode = true;
  487. installNewPlayerInterface(p, boost::none);
  488. GH.curInt = p.get();
  489. }
  490. battleStarted(gs->curB);
  491. }
  492. else
  493. {
  494. loadNeutralBattleAI();
  495. }
  496. serv->addStdVecItems(gs);
  497. hotSeat = (humanPlayers > 1);
  498. // std::vector<FileInfo> scriptModules;
  499. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
  500. // for(FileInfo &m : scriptModules)
  501. // {
  502. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  503. // privilagedGameEventReceivers.push_back(nm);
  504. // privilagedBattleEventReceivers.push_back(nm);
  505. // nm->giveActionCB(this);
  506. // nm->giveInfoCB(this);
  507. // nm->init();
  508. //
  509. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  510. // }
  511. }
  512. template <typename Handler>
  513. void CClient::serialize( Handler &h, const int version )
  514. {
  515. h & hotSeat;
  516. if(h.saving)
  517. {
  518. ui8 players = playerint.size();
  519. h & players;
  520. for(auto i = playerint.begin(); i != playerint.end(); i++)
  521. {
  522. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  523. assert(i->first == i->second->playerID);
  524. h & i->first & i->second->dllName & i->second->human;
  525. i->second->saveGame(dynamic_cast<COSer<CSaveFile>&>(h), version);
  526. //evil cast that i still like better than sfinae-magic. If I had a "static if"...
  527. }
  528. }
  529. else
  530. {
  531. ui8 players = 0; //fix for uninitialized warning
  532. h & players;
  533. for(int i=0; i < players; i++)
  534. {
  535. std::string dllname;
  536. PlayerColor pid;
  537. bool isHuman = false;
  538. h & pid & dllname & isHuman;
  539. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  540. shared_ptr<CGameInterface> nInt;
  541. if(dllname.length())
  542. {
  543. if(pid == PlayerColor::NEUTRAL)
  544. {
  545. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  546. //TODO? consider serialization
  547. continue;
  548. }
  549. else
  550. {
  551. assert(!isHuman);
  552. nInt = CDynLibHandler::getNewAI(dllname);
  553. }
  554. }
  555. else
  556. {
  557. assert(isHuman);
  558. nInt = make_shared<CPlayerInterface>(pid);
  559. }
  560. nInt->dllName = dllname;
  561. nInt->human = isHuman;
  562. nInt->playerID = pid;
  563. installNewPlayerInterface(nInt, pid);
  564. nInt->loadGame(dynamic_cast<CISer<CLoadFile>&>(h), version); //another evil cast, check above
  565. }
  566. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  567. loadNeutralBattleAI();
  568. }
  569. }
  570. template <typename Handler>
  571. void CClient::serialize( Handler &h, const int version, const std::set<PlayerColor>& playerIDs)
  572. {
  573. h & hotSeat;
  574. if(h.saving)
  575. {
  576. ui8 players = playerint.size();
  577. h & players;
  578. for(auto i = playerint.begin(); i != playerint.end(); i++)
  579. {
  580. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  581. assert(i->first == i->second->playerID);
  582. h & i->first & i->second->dllName & i->second->human;
  583. i->second->saveGame(dynamic_cast<COSer<CSaveFile>&>(h), version);
  584. //evil cast that i still like better than sfinae-magic. If I had a "static if"...
  585. }
  586. }
  587. else
  588. {
  589. ui8 players = 0; //fix for uninitialized warning
  590. h & players;
  591. for(int i=0; i < players; i++)
  592. {
  593. std::string dllname;
  594. PlayerColor pid;
  595. bool isHuman = false;
  596. h & pid & dllname & isHuman;
  597. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  598. shared_ptr<CGameInterface> nInt;
  599. if(dllname.length())
  600. {
  601. if(pid == PlayerColor::NEUTRAL)
  602. {
  603. if(playerIDs.count(pid))
  604. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  605. //TODO? consider serialization
  606. continue;
  607. }
  608. else
  609. {
  610. assert(!isHuman);
  611. nInt = CDynLibHandler::getNewAI(dllname);
  612. }
  613. }
  614. else
  615. {
  616. assert(isHuman);
  617. nInt = make_shared<CPlayerInterface>(pid);
  618. }
  619. nInt->dllName = dllname;
  620. nInt->human = isHuman;
  621. nInt->playerID = pid;
  622. if(playerIDs.count(pid))
  623. installNewPlayerInterface(nInt, pid);
  624. nInt->loadGame(dynamic_cast<CISer<CLoadFile>&>(h), version); //another evil cast, check above
  625. }
  626. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  627. loadNeutralBattleAI();
  628. }
  629. }
  630. void CClient::handlePack( CPack * pack )
  631. {
  632. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  633. if(apply)
  634. {
  635. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  636. apply->applyOnClBefore(this,pack);
  637. logNetwork->traceStream() << "\tMade first apply on cl";
  638. gs->apply(pack);
  639. logNetwork->traceStream() << "\tApplied on gs";
  640. apply->applyOnClAfter(this,pack);
  641. logNetwork->traceStream() << "\tMade second apply on cl";
  642. }
  643. else
  644. {
  645. logNetwork->errorStream() << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack);
  646. }
  647. delete pack;
  648. }
  649. void CClient::finishCampaign( shared_ptr<CCampaignState> camp )
  650. {
  651. }
  652. void CClient::proposeNextMission(shared_ptr<CCampaignState> camp)
  653. {
  654. GH.pushInt(new CBonusSelection(camp));
  655. }
  656. void CClient::stopConnection()
  657. {
  658. terminate = true;
  659. if (serv) //request closing connection
  660. {
  661. logNetwork->infoStream() << "Connection has been requested to be closed.";
  662. boost::unique_lock<boost::mutex>(*serv->wmx);
  663. CloseServer close_server;
  664. sendRequest(&close_server, PlayerColor::NEUTRAL);
  665. logNetwork->infoStream() << "Sent closing signal to the server";
  666. }
  667. if(connectionHandler)//end connection handler
  668. {
  669. if(connectionHandler->get_id() != boost::this_thread::get_id())
  670. connectionHandler->join();
  671. logNetwork->infoStream() << "Connection handler thread joined";
  672. delete connectionHandler;
  673. connectionHandler = nullptr;
  674. }
  675. if (serv) //and delete connection
  676. {
  677. serv->close();
  678. delete serv;
  679. serv = nullptr;
  680. logNetwork->warnStream() << "Our socket has been closed.";
  681. }
  682. }
  683. void CClient::battleStarted(const BattleInfo * info)
  684. {
  685. for(auto &battleCb : battleCallbacks)
  686. {
  687. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  688. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  689. {
  690. battleCb.second->setBattle(info);
  691. }
  692. }
  693. // for(ui8 side : info->sides)
  694. // if(battleCallbacks.count(side))
  695. // battleCallbacks[side]->setBattle(info);
  696. shared_ptr<CPlayerInterface> att, def;
  697. auto &leftSide = info->sides[0], &rightSide = info->sides[1];
  698. //If quick combat is not, do not prepare interfaces for battleint
  699. if(!settings["adventure"]["quickCombat"].Bool())
  700. {
  701. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  702. att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[leftSide.color] );
  703. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  704. def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[rightSide.color] );
  705. }
  706. if(!gNoGUI && (!!att || !!def || gs->scenarioOps->mode == StartInfo::DUEL))
  707. {
  708. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  709. auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
  710. Rect((screen->w - 800)/2,
  711. (screen->h - 600)/2, 800, 600), att, def);
  712. GH.pushInt(bi);
  713. }
  714. auto callBattleStart = [&](PlayerColor color, ui8 side){
  715. if(vstd::contains(battleints, color))
  716. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  717. };
  718. callBattleStart(leftSide.color, 0);
  719. callBattleStart(rightSide.color, 1);
  720. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  721. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide].color))
  722. {
  723. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
  724. }
  725. }
  726. void CClient::battleFinished()
  727. {
  728. for(auto & side : gs->curB->sides)
  729. if(battleCallbacks.count(side.color))
  730. battleCallbacks[side.color]->setBattle(nullptr);
  731. }
  732. void CClient::loadNeutralBattleAI()
  733. {
  734. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  735. }
  736. void CClient::commitPackage( CPackForClient *pack )
  737. {
  738. CommitPackage cp;
  739. cp.freePack = false;
  740. cp.packToCommit = pack;
  741. sendRequest(&cp, PlayerColor::NEUTRAL);
  742. }
  743. PlayerColor CClient::getLocalPlayer() const
  744. {
  745. if(LOCPLINT)
  746. return LOCPLINT->playerID;
  747. return getCurrentPlayer();
  748. }
  749. void CClient::commenceTacticPhaseForInt(shared_ptr<CBattleGameInterface> battleInt)
  750. {
  751. setThreadName("CClient::commenceTacticPhaseForInt");
  752. try
  753. {
  754. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  755. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  756. {
  757. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  758. sendRequest(&ma, battleInt->playerID);
  759. }
  760. } HANDLE_EXCEPTION
  761. }
  762. void CClient::invalidatePaths()
  763. {
  764. // turn pathfinding info into invalid. It will be regenerated later
  765. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  766. pathInfo->hero = nullptr;
  767. }
  768. const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance *h)
  769. {
  770. assert(h);
  771. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  772. if (pathInfo->hero != h)
  773. {
  774. gs->calculatePaths(h, *pathInfo.get());
  775. }
  776. return pathInfo.get();
  777. }
  778. int CClient::sendRequest(const CPack *request, PlayerColor player)
  779. {
  780. static ui32 requestCounter = 0;
  781. ui32 requestID = requestCounter++;
  782. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  783. % typeid(*request).name() % requestID;
  784. waitingRequest.pushBack(requestID);
  785. serv->sendPackToServer(*request, player, requestID);
  786. if(vstd::contains(playerint, player))
  787. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  788. return requestID;
  789. }
  790. void CClient::campaignMapFinished( shared_ptr<CCampaignState> camp )
  791. {
  792. endGame(false);
  793. GH.curInt = CGPreGame::create();
  794. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  795. auto finisher = [=]()
  796. {
  797. if(camp->mapsRemaining.size())
  798. proposeNextMission(camp);
  799. else
  800. finishCampaign(camp);
  801. };
  802. if(epilogue.hasPrologEpilog)
  803. {
  804. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  805. }
  806. else
  807. {
  808. finisher();
  809. }
  810. }
  811. void CClient::installNewPlayerInterface(shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color)
  812. {
  813. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  814. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  815. if(!color)
  816. privilagedGameEventReceivers.push_back(gameInterface);
  817. playerint[colorUsed] = gameInterface;
  818. logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed;
  819. auto cb = make_shared<CCallback>(gs, color, this);
  820. callbacks[colorUsed] = cb;
  821. battleCallbacks[colorUsed] = cb;
  822. gameInterface->init(cb);
  823. installNewBattleInterface(gameInterface, color, false);
  824. }
  825. void CClient::installNewBattleInterface(shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback /*= true*/)
  826. {
  827. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  828. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  829. if(!color)
  830. privilagedBattleEventReceivers.push_back(battleInterface);
  831. battleints[colorUsed] = battleInterface;
  832. if(needCallback)
  833. {
  834. logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color;
  835. auto cbc = make_shared<CBattleCallback>(gs, color, this);
  836. battleCallbacks[colorUsed] = cbc;
  837. battleInterface->init(cbc);
  838. }
  839. }
  840. std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
  841. {
  842. if(ps.name.size())
  843. {
  844. const boost::filesystem::path aiPath =
  845. VCMIDirs::get().libraryPath() / "AI" / VCMIDirs::get().libraryName(ps.name);
  846. if (boost::filesystem::exists(aiPath))
  847. return ps.name;
  848. }
  849. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  850. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  851. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  852. //TODO what about human players
  853. if(battleints.size() >= sensibleAILimit)
  854. return badAI;
  855. return goodAI;
  856. }
  857. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  858. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  859. void CServerHandler::startServer()
  860. {
  861. th.update();
  862. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  863. if(verbose)
  864. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  865. }
  866. void CServerHandler::waitForServer()
  867. {
  868. if(!serverThread)
  869. startServer();
  870. th.update();
  871. #ifndef VCMI_ANDROID
  872. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  873. while(!shared->sr->ready)
  874. {
  875. shared->sr->cond.wait(slock);
  876. }
  877. #endif
  878. if(verbose)
  879. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  880. }
  881. CConnection * CServerHandler::connectToServer()
  882. {
  883. #ifndef VCMI_ANDROID
  884. if(!shared->sr->ready)
  885. waitForServer();
  886. #else
  887. waitForServer();
  888. #endif
  889. th.update(); //put breakpoint here to attach to server before it does something stupid
  890. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  891. if(verbose)
  892. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  893. return ret;
  894. }
  895. CServerHandler::CServerHandler(bool runServer /*= false*/)
  896. {
  897. serverThread = nullptr;
  898. shared = nullptr;
  899. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  900. verbose = true;
  901. #ifndef VCMI_ANDROID
  902. boost::interprocess::shared_memory_object::remove("vcmi_memory"); //if the application has previously crashed, the memory may not have been removed. to avoid problems - try to destroy it
  903. try
  904. {
  905. shared = new SharedMem();
  906. } HANDLE_EXCEPTIONC(logNetwork->errorStream() << "Cannot open interprocess memory: ";)
  907. #endif
  908. }
  909. CServerHandler::~CServerHandler()
  910. {
  911. delete shared;
  912. delete serverThread; //detaches, not kills thread
  913. }
  914. void CServerHandler::callServer()
  915. {
  916. setThreadName("CServerHandler::callServer");
  917. const std::string logName = (VCMIDirs::get().userCachePath() / "server_log.txt").string();
  918. const std::string comm = VCMIDirs::get().serverPath().string() + " --port=" + port + " > \"" + logName + '\"';
  919. int result = std::system(comm.c_str());
  920. if (result == 0)
  921. logNetwork->infoStream() << "Server closed correctly";
  922. else
  923. {
  924. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  925. logNetwork->errorStream() << "Check " << logName << " for more info";
  926. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  927. }
  928. }
  929. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  930. {
  931. CConnection *ret = nullptr;
  932. while(!ret)
  933. {
  934. try
  935. {
  936. logNetwork->infoStream() << "Establishing connection...";
  937. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  938. port.size() ? port : boost::lexical_cast<std::string>(settings["server"]["port"].Float()),
  939. NAME);
  940. }
  941. catch(...)
  942. {
  943. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  944. SDL_Delay(2000);
  945. }
  946. }
  947. return ret;
  948. }