Client.cpp 28 KB

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