Client.cpp 29 KB

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