Client.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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 "CPreGame.h"
  32. #include "battle/CBattleInterface.h"
  33. #include "../lib/CThreadHelper.h"
  34. #include "../lib/CScriptingModule.h"
  35. #include "../lib/registerTypes/RegisterTypes.h"
  36. #include "gui/CGuiHandler.h"
  37. #include "CMT.h"
  38. extern std::string NAME;
  39. #ifndef VCMI_ANDROID
  40. namespace intpr = boost::interprocess;
  41. #endif
  42. /*
  43. * Client.cpp, part of VCMI engine
  44. *
  45. * Authors: listed in file AUTHORS in main folder
  46. *
  47. * License: GNU General Public License v2.0 or later
  48. * Full text of license available in license.txt file, in main folder
  49. *
  50. */
  51. template <typename T> class CApplyOnCL;
  52. class CBaseForCLApply
  53. {
  54. public:
  55. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  56. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  57. virtual ~CBaseForCLApply(){}
  58. template<typename U> static CBaseForCLApply *getApplier(const U * t=nullptr)
  59. {
  60. return new CApplyOnCL<U>;
  61. }
  62. };
  63. template <typename T> class CApplyOnCL : public CBaseForCLApply
  64. {
  65. public:
  66. void applyOnClAfter(CClient *cl, void *pack) const override
  67. {
  68. T *ptr = static_cast<T*>(pack);
  69. ptr->applyCl(cl);
  70. }
  71. void applyOnClBefore(CClient *cl, void *pack) const override
  72. {
  73. T *ptr = static_cast<T*>(pack);
  74. ptr->applyFirstCl(cl);
  75. }
  76. };
  77. template <> class CApplyOnCL<CPack> : public CBaseForCLApply
  78. {
  79. public:
  80. void applyOnClAfter(CClient *cl, void *pack) const override
  81. {
  82. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  83. assert(0);
  84. }
  85. void applyOnClBefore(CClient *cl, void *pack) const override
  86. {
  87. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  88. assert(0);
  89. }
  90. };
  91. static CApplier<CBaseForCLApply> *applier = nullptr;
  92. void CClient::init()
  93. {
  94. hotSeat = false;
  95. connectionHandler = nullptr;
  96. pathInfo = nullptr;
  97. applier = new CApplier<CBaseForCLApply>;
  98. registerTypesClientPacks1(*applier);
  99. registerTypesClientPacks2(*applier);
  100. IObjectInterface::cb = this;
  101. serv = nullptr;
  102. gs = nullptr;
  103. erm = nullptr;
  104. terminate = false;
  105. }
  106. CClient::CClient(void)
  107. {
  108. init();
  109. }
  110. CClient::CClient(CConnection *con, StartInfo *si)
  111. {
  112. init();
  113. newGame(con,si);
  114. }
  115. CClient::~CClient(void)
  116. {
  117. delete applier;
  118. }
  119. void CClient::waitForMoveAndSend(PlayerColor color)
  120. {
  121. try
  122. {
  123. setThreadName("CClient::waitForMoveAndSend");
  124. assert(vstd::contains(battleints, color));
  125. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  126. if(ba.actionType != Battle::CANCEL)
  127. {
  128. logNetwork->traceStream() << "Send battle action to server: " << ba;
  129. MakeAction temp_action(ba);
  130. sendRequest(&temp_action, color);
  131. }
  132. return;
  133. }
  134. catch(boost::thread_interrupted&)
  135. {
  136. logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
  137. return;
  138. }
  139. catch(...)
  140. {
  141. handleException();
  142. return;
  143. }
  144. logNetwork->errorStream() << "We should not be here!";
  145. }
  146. void CClient::run()
  147. {
  148. setThreadName("CClient::run");
  149. try
  150. {
  151. while(!terminate)
  152. {
  153. CPack *pack = serv->retreivePack(); //get the package from the server
  154. if (terminate)
  155. {
  156. vstd::clear_pointer(pack);
  157. break;
  158. }
  159. handlePack(pack);
  160. }
  161. }
  162. //catch only asio exceptions
  163. catch (const boost::system::system_error& e)
  164. {
  165. logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
  166. logNetwork->errorStream() << e.what();
  167. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  168. {
  169. logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
  170. throw;
  171. }
  172. }
  173. }
  174. void CClient::save(const std::string & fname)
  175. {
  176. if(gs->curB)
  177. {
  178. logNetwork->errorStream() << "Game cannot be saved during battle!";
  179. return;
  180. }
  181. SaveGame save_game(fname);
  182. sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
  183. }
  184. void CClient::endGame( bool closeConnection /*= true*/ )
  185. {
  186. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  187. for(auto i : playerint)
  188. i.second->finish();
  189. // Game is ending
  190. // Tell the network thread to reach a stable state
  191. if(closeConnection)
  192. stopConnection();
  193. logNetwork->infoStream() << "Closed connection.";
  194. GH.curInt = nullptr;
  195. {
  196. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  197. logNetwork->infoStream() << "Ending current game!";
  198. if(GH.topInt())
  199. {
  200. GH.topInt()->deactivate();
  201. }
  202. GH.listInt.clear();
  203. GH.objsToBlit.clear();
  204. GH.statusbar = nullptr;
  205. logNetwork->infoStream() << "Removed GUI.";
  206. vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
  207. vstd::clear_pointer(gs);
  208. logNetwork->infoStream() << "Deleted mapHandler and gameState.";
  209. LOCPLINT = nullptr;
  210. }
  211. playerint.clear();
  212. battleints.clear();
  213. callbacks.clear();
  214. battleCallbacks.clear();
  215. CGKeys::reset();
  216. CGMagi::reset();
  217. CGObelisk::reset();
  218. logNetwork->infoStream() << "Deleted playerInts.";
  219. logNetwork->infoStream() << "Client stopped.";
  220. }
  221. #if 1
  222. 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)
  223. {
  224. PlayerColor player(player_); //intentional shadowing
  225. logNetwork->infoStream() << "Loading procedure started!";
  226. std::string realPort;
  227. if(settings["testing"]["enabled"].Bool())
  228. realPort = settings["testing"]["port"].String();
  229. else if(port.size())
  230. realPort = port;
  231. else
  232. realPort = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  233. CServerHandler sh;
  234. if(server)
  235. sh.startServer();
  236. else
  237. serv = sh.justConnectToServer(ipaddr, realPort);
  238. CStopWatch tmh;
  239. std::unique_ptr<CLoadFile> loader;
  240. try
  241. {
  242. boost::filesystem::path clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  243. boost::filesystem::path controlServerSaveName;
  244. if (CResourceHandler::get("local")->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
  245. {
  246. controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  247. }
  248. else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  249. {
  250. controlServerSaveName = boost::filesystem::path(clientSaveName).replace_extension(".vsgm1");
  251. CResourceHandler::get("local")->createResource(controlServerSaveName.string(), true);
  252. }
  253. if(clientSaveName.empty())
  254. throw std::runtime_error("Cannot open client part of " + fname);
  255. if(controlServerSaveName.empty())
  256. throw std::runtime_error("Cannot open server part of " + fname);
  257. {
  258. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName, minSupportedVersion);
  259. loadCommonState(checkingLoader);
  260. loader = checkingLoader.decay();
  261. }
  262. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  263. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  264. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  265. pathInfo = make_unique<CPathsInfo>(getMapSize());
  266. CGI->mh->init();
  267. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  268. }
  269. catch(std::exception &e)
  270. {
  271. logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
  272. throw; //obviously we cannot continue here
  273. }
  274. /*
  275. if(!server)
  276. player = PlayerColor(player_);
  277. */
  278. std::set<PlayerColor> clientPlayers;
  279. if(server)
  280. serv = sh.connectToServer();
  281. //*loader >> *this;
  282. if(server)
  283. {
  284. tmh.update();
  285. ui8 pom8;
  286. *serv << ui8(3) << ui8(loadNumPlayers); //load game; one client if single-player
  287. *serv << fname;
  288. *serv >> pom8;
  289. if(pom8)
  290. throw std::runtime_error("Server cannot open the savegame!");
  291. else
  292. logNetwork->infoStream() << "Server opened savegame properly.";
  293. }
  294. if(server)
  295. {
  296. for(auto & elem : gs->scenarioOps->playerInfos)
  297. {
  298. if(!std::count(humanplayerindices.begin(),humanplayerindices.end(),elem.first.getNum()) || elem.first==player)
  299. clientPlayers.insert(elem.first);
  300. }
  301. clientPlayers.insert(PlayerColor::NEUTRAL);
  302. }
  303. else
  304. {
  305. clientPlayers.insert(player);
  306. }
  307. std::cout << "CLIENTPLAYERS:\n";
  308. for(auto x : clientPlayers)
  309. std::cout << x << std::endl;
  310. std::cout << "ENDCLIENTPLAYERS\n";
  311. serialize(loader->serializer,0,clientPlayers);
  312. *serv << ui32(clientPlayers.size());
  313. for(auto & elem : clientPlayers)
  314. *serv << ui8(elem.getNum());
  315. serv->addStdVecItems(gs); /*why is this here?*/
  316. //*loader >> *this;
  317. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  318. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  319. //*serv << clientPlayers;
  320. serv->enableStackSendingByID();
  321. serv->disableSmartPointerSerialization();
  322. // logGlobal->traceStream() << "Objects:";
  323. // for(int i = 0; i < gs->map->objects.size(); i++)
  324. // {
  325. // auto o = gs->map->objects[i];
  326. // if(o)
  327. // logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
  328. // else
  329. // logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
  330. // }
  331. }
  332. #endif
  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(std::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 = std::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. void CClient::serialize(COSer & h, const int version)
  454. {
  455. assert(h.saving);
  456. h & hotSeat;
  457. {
  458. ui8 players = playerint.size();
  459. h & players;
  460. for(auto i = playerint.begin(); i != playerint.end(); i++)
  461. {
  462. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  463. assert(i->first == i->second->playerID);
  464. h & i->first & i->second->dllName & i->second->human;
  465. i->second->saveGame(h, version);
  466. }
  467. }
  468. }
  469. void CClient::serialize(CISer & h, const int version)
  470. {
  471. assert(!h.saving);
  472. h & hotSeat;
  473. {
  474. ui8 players = 0; //fix for uninitialized warning
  475. h & players;
  476. for(int i=0; i < players; i++)
  477. {
  478. std::string dllname;
  479. PlayerColor pid;
  480. bool isHuman = false;
  481. h & pid & dllname & isHuman;
  482. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  483. std::shared_ptr<CGameInterface> nInt;
  484. if(dllname.length())
  485. {
  486. if(pid == PlayerColor::NEUTRAL)
  487. {
  488. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  489. //TODO? consider serialization
  490. continue;
  491. }
  492. else
  493. {
  494. assert(!isHuman);
  495. nInt = CDynLibHandler::getNewAI(dllname);
  496. }
  497. }
  498. else
  499. {
  500. assert(isHuman);
  501. nInt = std::make_shared<CPlayerInterface>(pid);
  502. }
  503. nInt->dllName = dllname;
  504. nInt->human = isHuman;
  505. nInt->playerID = pid;
  506. installNewPlayerInterface(nInt, pid);
  507. nInt->loadGame(h, version); //another evil cast, check above
  508. }
  509. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  510. loadNeutralBattleAI();
  511. }
  512. }
  513. void CClient::serialize(COSer & h, const int version, const std::set<PlayerColor> & playerIDs)
  514. {
  515. assert(h.saving);
  516. h & hotSeat;
  517. {
  518. ui8 players = playerint.size();
  519. h & players;
  520. for(auto i = playerint.begin(); i != playerint.end(); i++)
  521. {
  522. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  523. assert(i->first == i->second->playerID);
  524. h & i->first & i->second->dllName & i->second->human;
  525. i->second->saveGame(h, version);
  526. }
  527. }
  528. }
  529. void CClient::serialize(CISer & h, const int version, const std::set<PlayerColor> & playerIDs)
  530. {
  531. assert(!h.saving);
  532. h & hotSeat;
  533. {
  534. ui8 players = 0; //fix for uninitialized warning
  535. h & players;
  536. for(int i=0; i < players; i++)
  537. {
  538. std::string dllname;
  539. PlayerColor pid;
  540. bool isHuman = false;
  541. h & pid & dllname & isHuman;
  542. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  543. std::shared_ptr<CGameInterface> nInt;
  544. if(dllname.length())
  545. {
  546. if(pid == PlayerColor::NEUTRAL)
  547. {
  548. if(playerIDs.count(pid))
  549. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  550. //TODO? consider serialization
  551. continue;
  552. }
  553. else
  554. {
  555. assert(!isHuman);
  556. nInt = CDynLibHandler::getNewAI(dllname);
  557. }
  558. }
  559. else
  560. {
  561. assert(isHuman);
  562. nInt = std::make_shared<CPlayerInterface>(pid);
  563. }
  564. nInt->dllName = dllname;
  565. nInt->human = isHuman;
  566. nInt->playerID = pid;
  567. if(playerIDs.count(pid))
  568. installNewPlayerInterface(nInt, pid);
  569. nInt->loadGame(h, version);
  570. }
  571. if(playerIDs.count(PlayerColor::NEUTRAL))
  572. loadNeutralBattleAI();
  573. }
  574. }
  575. void CClient::handlePack( CPack * pack )
  576. {
  577. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  578. if(apply)
  579. {
  580. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  581. apply->applyOnClBefore(this,pack);
  582. logNetwork->traceStream() << "\tMade first apply on cl";
  583. gs->apply(pack);
  584. logNetwork->traceStream() << "\tApplied on gs";
  585. apply->applyOnClAfter(this,pack);
  586. logNetwork->traceStream() << "\tMade second apply on cl";
  587. }
  588. else
  589. {
  590. logNetwork->errorStream() << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack);
  591. }
  592. delete pack;
  593. }
  594. void CClient::finishCampaign( std::shared_ptr<CCampaignState> camp )
  595. {
  596. }
  597. void CClient::proposeNextMission(std::shared_ptr<CCampaignState> camp)
  598. {
  599. GH.pushInt(new CBonusSelection(camp));
  600. }
  601. void CClient::stopConnection()
  602. {
  603. terminate = true;
  604. if (serv) //request closing connection
  605. {
  606. logNetwork->infoStream() << "Connection has been requested to be closed.";
  607. boost::unique_lock<boost::mutex>(*serv->wmx);
  608. CloseServer close_server;
  609. sendRequest(&close_server, PlayerColor::NEUTRAL);
  610. logNetwork->infoStream() << "Sent closing signal to the server";
  611. }
  612. if(connectionHandler)//end connection handler
  613. {
  614. if(connectionHandler->get_id() != boost::this_thread::get_id())
  615. connectionHandler->join();
  616. logNetwork->infoStream() << "Connection handler thread joined";
  617. delete connectionHandler;
  618. connectionHandler = nullptr;
  619. }
  620. if (serv) //and delete connection
  621. {
  622. serv->close();
  623. delete serv;
  624. serv = nullptr;
  625. logNetwork->warnStream() << "Our socket has been closed.";
  626. }
  627. }
  628. void CClient::battleStarted(const BattleInfo * info)
  629. {
  630. for(auto &battleCb : battleCallbacks)
  631. {
  632. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  633. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  634. {
  635. battleCb.second->setBattle(info);
  636. }
  637. }
  638. // for(ui8 side : info->sides)
  639. // if(battleCallbacks.count(side))
  640. // battleCallbacks[side]->setBattle(info);
  641. std::shared_ptr<CPlayerInterface> att, def;
  642. auto &leftSide = info->sides[0], &rightSide = info->sides[1];
  643. //If quick combat is not, do not prepare interfaces for battleint
  644. if(!settings["adventure"]["quickCombat"].Bool())
  645. {
  646. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  647. att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[leftSide.color] );
  648. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  649. def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[rightSide.color] );
  650. }
  651. if(!gNoGUI && (!!att || !!def || gs->scenarioOps->mode == StartInfo::DUEL))
  652. {
  653. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  654. auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
  655. Rect((screen->w - 800)/2,
  656. (screen->h - 600)/2, 800, 600), att, def);
  657. GH.pushInt(bi);
  658. }
  659. auto callBattleStart = [&](PlayerColor color, ui8 side){
  660. if(vstd::contains(battleints, color))
  661. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  662. };
  663. callBattleStart(leftSide.color, 0);
  664. callBattleStart(rightSide.color, 1);
  665. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  666. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide].color))
  667. {
  668. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
  669. }
  670. }
  671. void CClient::battleFinished()
  672. {
  673. for(auto & side : gs->curB->sides)
  674. if(battleCallbacks.count(side.color))
  675. battleCallbacks[side.color]->setBattle(nullptr);
  676. }
  677. void CClient::loadNeutralBattleAI()
  678. {
  679. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  680. }
  681. void CClient::commitPackage( CPackForClient *pack )
  682. {
  683. CommitPackage cp;
  684. cp.freePack = false;
  685. cp.packToCommit = pack;
  686. sendRequest(&cp, PlayerColor::NEUTRAL);
  687. }
  688. PlayerColor CClient::getLocalPlayer() const
  689. {
  690. if(LOCPLINT)
  691. return LOCPLINT->playerID;
  692. return getCurrentPlayer();
  693. }
  694. void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
  695. {
  696. setThreadName("CClient::commenceTacticPhaseForInt");
  697. try
  698. {
  699. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  700. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  701. {
  702. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  703. sendRequest(&ma, battleInt->playerID);
  704. }
  705. }
  706. catch(...)
  707. {
  708. handleException();
  709. }
  710. }
  711. void CClient::invalidatePaths()
  712. {
  713. // turn pathfinding info into invalid. It will be regenerated later
  714. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  715. pathInfo->hero = nullptr;
  716. }
  717. const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance *h)
  718. {
  719. assert(h);
  720. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  721. if (pathInfo->hero != h)
  722. {
  723. gs->calculatePaths(h, *pathInfo.get());
  724. }
  725. return pathInfo.get();
  726. }
  727. int CClient::sendRequest(const CPack *request, PlayerColor player)
  728. {
  729. static ui32 requestCounter = 0;
  730. ui32 requestID = requestCounter++;
  731. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  732. % typeid(*request).name() % requestID;
  733. waitingRequest.pushBack(requestID);
  734. serv->sendPackToServer(*request, player, requestID);
  735. if(vstd::contains(playerint, player))
  736. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  737. return requestID;
  738. }
  739. void CClient::campaignMapFinished( std::shared_ptr<CCampaignState> camp )
  740. {
  741. endGame(false);
  742. GH.curInt = CGPreGame::create();
  743. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  744. auto finisher = [=]()
  745. {
  746. if(camp->mapsRemaining.size())
  747. proposeNextMission(camp);
  748. else
  749. finishCampaign(camp);
  750. };
  751. if(epilogue.hasPrologEpilog)
  752. {
  753. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  754. }
  755. else
  756. {
  757. finisher();
  758. }
  759. }
  760. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color)
  761. {
  762. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  763. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  764. if(!color)
  765. privilagedGameEventReceivers.push_back(gameInterface);
  766. playerint[colorUsed] = gameInterface;
  767. logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed;
  768. auto cb = std::make_shared<CCallback>(gs, color, this);
  769. callbacks[colorUsed] = cb;
  770. battleCallbacks[colorUsed] = cb;
  771. gameInterface->init(cb);
  772. installNewBattleInterface(gameInterface, color, false);
  773. }
  774. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback /*= true*/)
  775. {
  776. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  777. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  778. if(!color)
  779. privilagedBattleEventReceivers.push_back(battleInterface);
  780. battleints[colorUsed] = battleInterface;
  781. if(needCallback)
  782. {
  783. logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color;
  784. auto cbc = std::make_shared<CBattleCallback>(gs, color, this);
  785. battleCallbacks[colorUsed] = cbc;
  786. battleInterface->init(cbc);
  787. }
  788. }
  789. std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
  790. {
  791. if(ps.name.size())
  792. {
  793. const boost::filesystem::path aiPath =
  794. VCMIDirs::get().libraryPath() / "AI" / VCMIDirs::get().libraryName(ps.name);
  795. if (boost::filesystem::exists(aiPath))
  796. return ps.name;
  797. }
  798. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  799. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  800. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  801. //TODO what about human players
  802. if(battleints.size() >= sensibleAILimit)
  803. return badAI;
  804. return goodAI;
  805. }
  806. bool CServerHandler::DO_NOT_START_SERVER = false;
  807. void CServerHandler::startServer()
  808. {
  809. if(DO_NOT_START_SERVER)
  810. return;
  811. th.update();
  812. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  813. if(verbose)
  814. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  815. }
  816. void CServerHandler::waitForServer()
  817. {
  818. if(DO_NOT_START_SERVER)
  819. return;
  820. if(!serverThread)
  821. startServer();
  822. th.update();
  823. #ifndef VCMI_ANDROID
  824. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  825. while(!shared->sr->ready)
  826. {
  827. shared->sr->cond.wait(slock);
  828. }
  829. #endif
  830. if(verbose)
  831. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  832. }
  833. CConnection * CServerHandler::connectToServer()
  834. {
  835. #ifndef VCMI_ANDROID
  836. if(!shared->sr->ready)
  837. waitForServer();
  838. #else
  839. waitForServer();
  840. #endif
  841. th.update(); //put breakpoint here to attach to server before it does something stupid
  842. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  843. if(verbose)
  844. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  845. return ret;
  846. }
  847. CServerHandler::CServerHandler(bool runServer /*= false*/)
  848. {
  849. serverThread = nullptr;
  850. shared = nullptr;
  851. if(settings["testing"]["enabled"].Bool())
  852. port = settings["testing"]["port"].String();
  853. else
  854. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  855. verbose = true;
  856. #ifndef VCMI_ANDROID
  857. 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
  858. try
  859. {
  860. shared = new SharedMem();
  861. }
  862. catch(...)
  863. {
  864. logNetwork->error("Cannot open interprocess memory.");
  865. handleException();
  866. throw;
  867. }
  868. #endif
  869. }
  870. CServerHandler::~CServerHandler()
  871. {
  872. delete shared;
  873. delete serverThread; //detaches, not kills thread
  874. }
  875. void CServerHandler::callServer()
  876. {
  877. setThreadName("CServerHandler::callServer");
  878. const std::string logName = (VCMIDirs::get().userCachePath() / "server_log.txt").string();
  879. const std::string comm = VCMIDirs::get().serverPath().string() + " --port=" + port + " > \"" + logName + '\"';
  880. int result = std::system(comm.c_str());
  881. if (result == 0)
  882. logNetwork->infoStream() << "Server closed correctly";
  883. else
  884. {
  885. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  886. logNetwork->errorStream() << "Check " << logName << " for more info";
  887. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  888. }
  889. }
  890. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  891. {
  892. std::string realPort;
  893. if(settings["testing"]["enabled"].Bool())
  894. realPort = settings["testing"]["port"].String();
  895. else if(port.size())
  896. realPort = port;
  897. else
  898. realPort = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  899. CConnection *ret = nullptr;
  900. while(!ret)
  901. {
  902. try
  903. {
  904. logNetwork->infoStream() << "Establishing connection...";
  905. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  906. realPort,
  907. NAME);
  908. }
  909. catch(...)
  910. {
  911. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  912. SDL_Delay(2000);
  913. }
  914. }
  915. return ret;
  916. }