Client.cpp 26 KB

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