Client.cpp 32 KB

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