Client.cpp 29 KB

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