Client.cpp 29 KB

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