Client.cpp 29 KB

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