2
0

Client.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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. void CClient::serialize(COSer & h, const int version)
  436. {
  437. assert(h.saving);
  438. h & hotSeat;
  439. {
  440. ui8 players = playerint.size();
  441. h & players;
  442. for(auto i = playerint.begin(); i != playerint.end(); i++)
  443. {
  444. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  445. assert(i->first == i->second->playerID);
  446. h & i->first & i->second->dllName & i->second->human;
  447. i->second->saveGame(h, version);
  448. }
  449. }
  450. }
  451. void CClient::serialize(CISer & h, const int version)
  452. {
  453. assert(!h.saving);
  454. h & hotSeat;
  455. {
  456. ui8 players = 0; //fix for uninitialized warning
  457. h & players;
  458. for(int i=0; i < players; i++)
  459. {
  460. std::string dllname;
  461. PlayerColor pid;
  462. bool isHuman = false;
  463. h & pid & dllname & isHuman;
  464. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  465. shared_ptr<CGameInterface> nInt;
  466. if(dllname.length())
  467. {
  468. if(pid == PlayerColor::NEUTRAL)
  469. {
  470. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  471. //TODO? consider serialization
  472. continue;
  473. }
  474. else
  475. {
  476. assert(!isHuman);
  477. nInt = CDynLibHandler::getNewAI(dllname);
  478. }
  479. }
  480. else
  481. {
  482. assert(isHuman);
  483. nInt = make_shared<CPlayerInterface>(pid);
  484. }
  485. nInt->dllName = dllname;
  486. nInt->human = isHuman;
  487. nInt->playerID = pid;
  488. installNewPlayerInterface(nInt, pid);
  489. nInt->loadGame(h, version); //another evil cast, check above
  490. }
  491. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  492. loadNeutralBattleAI();
  493. }
  494. }
  495. void CClient::serialize(COSer & h, const int version, const std::set<PlayerColor> & playerIDs)
  496. {
  497. assert(h.saving);
  498. h & hotSeat;
  499. {
  500. ui8 players = playerint.size();
  501. h & players;
  502. for(auto i = playerint.begin(); i != playerint.end(); i++)
  503. {
  504. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  505. assert(i->first == i->second->playerID);
  506. h & i->first & i->second->dllName & i->second->human;
  507. i->second->saveGame(h, version);
  508. }
  509. }
  510. }
  511. void CClient::serialize(CISer & h, const int version, const std::set<PlayerColor> & playerIDs)
  512. {
  513. assert(!h.saving);
  514. h & hotSeat;
  515. {
  516. ui8 players = 0; //fix for uninitialized warning
  517. h & players;
  518. for(int i=0; i < players; i++)
  519. {
  520. std::string dllname;
  521. PlayerColor pid;
  522. bool isHuman = false;
  523. h & pid & dllname & isHuman;
  524. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  525. shared_ptr<CGameInterface> nInt;
  526. if(dllname.length())
  527. {
  528. if(pid == PlayerColor::NEUTRAL)
  529. {
  530. if(playerIDs.count(pid))
  531. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  532. //TODO? consider serialization
  533. continue;
  534. }
  535. else
  536. {
  537. assert(!isHuman);
  538. nInt = CDynLibHandler::getNewAI(dllname);
  539. }
  540. }
  541. else
  542. {
  543. assert(isHuman);
  544. nInt = make_shared<CPlayerInterface>(pid);
  545. }
  546. nInt->dllName = dllname;
  547. nInt->human = isHuman;
  548. nInt->playerID = pid;
  549. if(playerIDs.count(pid))
  550. installNewPlayerInterface(nInt, pid);
  551. nInt->loadGame(h, version);
  552. }
  553. if(playerIDs.count(PlayerColor::NEUTRAL))
  554. loadNeutralBattleAI();
  555. }
  556. }
  557. void CClient::handlePack( CPack * pack )
  558. {
  559. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  560. if(apply)
  561. {
  562. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  563. apply->applyOnClBefore(this,pack);
  564. logNetwork->traceStream() << "\tMade first apply on cl";
  565. gs->apply(pack);
  566. logNetwork->traceStream() << "\tApplied on gs";
  567. apply->applyOnClAfter(this,pack);
  568. logNetwork->traceStream() << "\tMade second apply on cl";
  569. }
  570. else
  571. {
  572. logNetwork->errorStream() << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack);
  573. }
  574. delete pack;
  575. }
  576. void CClient::finishCampaign( shared_ptr<CCampaignState> camp )
  577. {
  578. }
  579. void CClient::proposeNextMission(shared_ptr<CCampaignState> camp)
  580. {
  581. GH.pushInt(new CBonusSelection(camp));
  582. }
  583. void CClient::stopConnection()
  584. {
  585. terminate = true;
  586. if (serv) //request closing connection
  587. {
  588. logNetwork->infoStream() << "Connection has been requested to be closed.";
  589. boost::unique_lock<boost::mutex>(*serv->wmx);
  590. CloseServer close_server;
  591. sendRequest(&close_server, PlayerColor::NEUTRAL);
  592. logNetwork->infoStream() << "Sent closing signal to the server";
  593. }
  594. if(connectionHandler)//end connection handler
  595. {
  596. if(connectionHandler->get_id() != boost::this_thread::get_id())
  597. connectionHandler->join();
  598. logNetwork->infoStream() << "Connection handler thread joined";
  599. delete connectionHandler;
  600. connectionHandler = nullptr;
  601. }
  602. if (serv) //and delete connection
  603. {
  604. serv->close();
  605. delete serv;
  606. serv = nullptr;
  607. logNetwork->warnStream() << "Our socket has been closed.";
  608. }
  609. }
  610. void CClient::battleStarted(const BattleInfo * info)
  611. {
  612. for(auto &battleCb : battleCallbacks)
  613. {
  614. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  615. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  616. {
  617. battleCb.second->setBattle(info);
  618. }
  619. }
  620. // for(ui8 side : info->sides)
  621. // if(battleCallbacks.count(side))
  622. // battleCallbacks[side]->setBattle(info);
  623. shared_ptr<CPlayerInterface> att, def;
  624. auto &leftSide = info->sides[0], &rightSide = info->sides[1];
  625. //If quick combat is not, do not prepare interfaces for battleint
  626. if(!settings["adventure"]["quickCombat"].Bool())
  627. {
  628. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  629. att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[leftSide.color] );
  630. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  631. def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[rightSide.color] );
  632. }
  633. if(!gNoGUI && (!!att || !!def || gs->scenarioOps->mode == StartInfo::DUEL))
  634. {
  635. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  636. auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
  637. Rect((screen->w - 800)/2,
  638. (screen->h - 600)/2, 800, 600), att, def);
  639. GH.pushInt(bi);
  640. }
  641. auto callBattleStart = [&](PlayerColor color, ui8 side){
  642. if(vstd::contains(battleints, color))
  643. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  644. };
  645. callBattleStart(leftSide.color, 0);
  646. callBattleStart(rightSide.color, 1);
  647. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  648. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide].color))
  649. {
  650. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
  651. }
  652. }
  653. void CClient::battleFinished()
  654. {
  655. for(auto & side : gs->curB->sides)
  656. if(battleCallbacks.count(side.color))
  657. battleCallbacks[side.color]->setBattle(nullptr);
  658. }
  659. void CClient::loadNeutralBattleAI()
  660. {
  661. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  662. }
  663. void CClient::commitPackage( CPackForClient *pack )
  664. {
  665. CommitPackage cp;
  666. cp.freePack = false;
  667. cp.packToCommit = pack;
  668. sendRequest(&cp, PlayerColor::NEUTRAL);
  669. }
  670. PlayerColor CClient::getLocalPlayer() const
  671. {
  672. if(LOCPLINT)
  673. return LOCPLINT->playerID;
  674. return getCurrentPlayer();
  675. }
  676. void CClient::commenceTacticPhaseForInt(shared_ptr<CBattleGameInterface> battleInt)
  677. {
  678. setThreadName("CClient::commenceTacticPhaseForInt");
  679. try
  680. {
  681. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  682. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  683. {
  684. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  685. sendRequest(&ma, battleInt->playerID);
  686. }
  687. } HANDLE_EXCEPTION
  688. }
  689. void CClient::invalidatePaths()
  690. {
  691. // turn pathfinding info into invalid. It will be regenerated later
  692. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  693. pathInfo->hero = nullptr;
  694. }
  695. const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance *h)
  696. {
  697. assert(h);
  698. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  699. if (pathInfo->hero != h)
  700. {
  701. gs->calculatePaths(h, *pathInfo.get());
  702. }
  703. return pathInfo.get();
  704. }
  705. int CClient::sendRequest(const CPack *request, PlayerColor player)
  706. {
  707. static ui32 requestCounter = 0;
  708. ui32 requestID = requestCounter++;
  709. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  710. % typeid(*request).name() % requestID;
  711. waitingRequest.pushBack(requestID);
  712. serv->sendPackToServer(*request, player, requestID);
  713. if(vstd::contains(playerint, player))
  714. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  715. return requestID;
  716. }
  717. void CClient::campaignMapFinished( shared_ptr<CCampaignState> camp )
  718. {
  719. endGame(false);
  720. GH.curInt = CGPreGame::create();
  721. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  722. auto finisher = [=]()
  723. {
  724. if(camp->mapsRemaining.size())
  725. proposeNextMission(camp);
  726. else
  727. finishCampaign(camp);
  728. };
  729. if(epilogue.hasPrologEpilog)
  730. {
  731. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  732. }
  733. else
  734. {
  735. finisher();
  736. }
  737. }
  738. void CClient::installNewPlayerInterface(shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color)
  739. {
  740. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  741. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  742. if(!color)
  743. privilagedGameEventReceivers.push_back(gameInterface);
  744. playerint[colorUsed] = gameInterface;
  745. logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed;
  746. auto cb = make_shared<CCallback>(gs, color, this);
  747. callbacks[colorUsed] = cb;
  748. battleCallbacks[colorUsed] = cb;
  749. gameInterface->init(cb);
  750. installNewBattleInterface(gameInterface, color, false);
  751. }
  752. void CClient::installNewBattleInterface(shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback /*= true*/)
  753. {
  754. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  755. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  756. if(!color)
  757. privilagedBattleEventReceivers.push_back(battleInterface);
  758. battleints[colorUsed] = battleInterface;
  759. if(needCallback)
  760. {
  761. logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color;
  762. auto cbc = make_shared<CBattleCallback>(gs, color, this);
  763. battleCallbacks[colorUsed] = cbc;
  764. battleInterface->init(cbc);
  765. }
  766. }
  767. std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
  768. {
  769. if(ps.name.size())
  770. {
  771. const boost::filesystem::path aiPath =
  772. VCMIDirs::get().libraryPath() / "AI" / VCMIDirs::get().libraryName(ps.name);
  773. if (boost::filesystem::exists(aiPath))
  774. return ps.name;
  775. }
  776. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  777. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  778. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  779. //TODO what about human players
  780. if(battleints.size() >= sensibleAILimit)
  781. return badAI;
  782. return goodAI;
  783. }
  784. void CServerHandler::startServer()
  785. {
  786. th.update();
  787. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  788. if(verbose)
  789. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  790. }
  791. void CServerHandler::waitForServer()
  792. {
  793. if(!serverThread)
  794. startServer();
  795. th.update();
  796. #ifndef VCMI_ANDROID
  797. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  798. while(!shared->sr->ready)
  799. {
  800. shared->sr->cond.wait(slock);
  801. }
  802. #endif
  803. if(verbose)
  804. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  805. }
  806. CConnection * CServerHandler::connectToServer()
  807. {
  808. #ifndef VCMI_ANDROID
  809. if(!shared->sr->ready)
  810. waitForServer();
  811. #else
  812. waitForServer();
  813. #endif
  814. th.update(); //put breakpoint here to attach to server before it does something stupid
  815. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  816. if(verbose)
  817. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  818. return ret;
  819. }
  820. CServerHandler::CServerHandler(bool runServer /*= false*/)
  821. {
  822. serverThread = nullptr;
  823. shared = nullptr;
  824. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  825. verbose = true;
  826. #ifndef VCMI_ANDROID
  827. 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
  828. try
  829. {
  830. shared = new SharedMem();
  831. } HANDLE_EXCEPTIONC(logNetwork->errorStream() << "Cannot open interprocess memory: ";)
  832. #endif
  833. }
  834. CServerHandler::~CServerHandler()
  835. {
  836. delete shared;
  837. delete serverThread; //detaches, not kills thread
  838. }
  839. void CServerHandler::callServer()
  840. {
  841. setThreadName("CServerHandler::callServer");
  842. const std::string logName = (VCMIDirs::get().userCachePath() / "server_log.txt").string();
  843. const std::string comm = VCMIDirs::get().serverPath().string() + " --port=" + port + " > \"" + logName + '\"';
  844. int result = std::system(comm.c_str());
  845. if (result == 0)
  846. logNetwork->infoStream() << "Server closed correctly";
  847. else
  848. {
  849. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  850. logNetwork->errorStream() << "Check " << logName << " for more info";
  851. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  852. }
  853. }
  854. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  855. {
  856. CConnection *ret = nullptr;
  857. while(!ret)
  858. {
  859. try
  860. {
  861. logNetwork->infoStream() << "Establishing connection...";
  862. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  863. port.size() ? port : boost::lexical_cast<std::string>(settings["server"]["port"].Float()),
  864. NAME);
  865. }
  866. catch(...)
  867. {
  868. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  869. SDL_Delay(2000);
  870. }
  871. }
  872. return ret;
  873. }