Client.cpp 25 KB

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