Client.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. #include "../hch/CMusicHandler.h"
  2. #include "../hch/CCampaignHandler.h"
  3. #include "../CCallback.h"
  4. #include "../CConsoleHandler.h"
  5. #include "CGameInfo.h"
  6. #include "../lib/CGameState.h"
  7. #include "CPlayerInterface.h"
  8. #include "../StartInfo.h"
  9. #include "../hch/CArtHandler.h"
  10. #include "../hch/CDefObjInfoHandler.h"
  11. #include "../hch/CGeneralTextHandler.h"
  12. #include "../hch/CHeroHandler.h"
  13. #include "../hch/CTownHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CBuildingHandler.h"
  16. #include "../hch/CSpellHandler.h"
  17. #include "../lib/Connection.h"
  18. #include "../lib/Interprocess.h"
  19. #include "../lib/NetPacks.h"
  20. #include "../lib/VCMI_Lib.h"
  21. #include "../lib/map.h"
  22. #include "mapHandler.h"
  23. #include "CConfigHandler.h"
  24. #include "Client.h"
  25. #include "GUIBase.h"
  26. #include <boost/bind.hpp>
  27. #include <boost/foreach.hpp>
  28. #include <boost/thread.hpp>
  29. #include <boost/thread/shared_mutex.hpp>
  30. #include <boost/lexical_cast.hpp>
  31. #include <sstream>
  32. #include "CPreGame.h"
  33. #define NOT_LIB
  34. #include "../lib/RegisterTypes.cpp"
  35. extern std::string NAME;
  36. namespace intpr = boost::interprocess;
  37. /*
  38. * Client.cpp, part of VCMI engine
  39. *
  40. * Authors: listed in file AUTHORS in main folder
  41. *
  42. * License: GNU General Public License v2.0 or later
  43. * Full text of license available in license.txt file, in main folder
  44. *
  45. */
  46. template <typename T> class CApplyOnCL;
  47. class CBaseForCLApply
  48. {
  49. public:
  50. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  51. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  52. virtual ~CBaseForCLApply(){}
  53. template<typename U> static CBaseForCLApply *getApplier(const U * t=NULL)
  54. {
  55. return new CApplyOnCL<U>;
  56. }
  57. };
  58. template <typename T> class CApplyOnCL : public CBaseForCLApply
  59. {
  60. public:
  61. void applyOnClAfter(CClient *cl, void *pack) const
  62. {
  63. T *ptr = static_cast<T*>(pack);
  64. ptr->applyCl(cl);
  65. }
  66. void applyOnClBefore(CClient *cl, void *pack) const
  67. {
  68. T *ptr = static_cast<T*>(pack);
  69. ptr->applyFirstCl(cl);
  70. }
  71. };
  72. static CApplier<CBaseForCLApply> *applier = NULL;
  73. void CClient::init()
  74. {
  75. hotSeat = false;
  76. connectionHandler = NULL;
  77. pathInfo = NULL;
  78. applier = new CApplier<CBaseForCLApply>;
  79. registerTypes2(*applier);
  80. IObjectInterface::cb = this;
  81. serv = NULL;
  82. gs = NULL;
  83. cb = NULL;
  84. terminate = false;
  85. }
  86. CClient::CClient(void)
  87. :waitingRequest(false)
  88. {
  89. init();
  90. }
  91. CClient::CClient(CConnection *con, StartInfo *si)
  92. :waitingRequest(false)
  93. {
  94. init();
  95. newGame(con,si);
  96. }
  97. CClient::~CClient(void)
  98. {
  99. delete pathInfo;
  100. delete applier;
  101. }
  102. void CClient::waitForMoveAndSend(int color)
  103. {
  104. try
  105. {
  106. BattleAction ba = playerint[color]->activeStack(gs->curB->activeStack);
  107. *serv << &MakeAction(ba);
  108. return;
  109. }HANDLE_EXCEPTION
  110. tlog1 << "We should not be here!" << std::endl;
  111. }
  112. void CClient::run()
  113. {
  114. try
  115. {
  116. CPack *pack = NULL;
  117. while(!terminate)
  118. {
  119. pack = serv->retreivePack(); //get the package from the server
  120. if (terminate)
  121. {
  122. delete pack;
  123. pack = NULL;
  124. break;
  125. }
  126. handlePack(pack);
  127. pack = NULL;
  128. }
  129. }
  130. catch (const std::exception& e)
  131. {
  132. tlog3 << "Lost connection to server, ending listening thread!\n";
  133. tlog1 << e.what() << std::endl;
  134. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  135. {
  136. tlog1 << "Something wrong, lost connection while game is still ongoing...\n";
  137. throw;
  138. }
  139. }
  140. }
  141. void CClient::save(const std::string & fname)
  142. {
  143. if(gs->curB)
  144. {
  145. tlog1 << "Game cannot be saved during battle!\n";
  146. return;
  147. }
  148. *serv << &SaveGame(fname);
  149. }
  150. #include <fstream>
  151. void initVillagesCapitols(Mapa * map)
  152. {
  153. std::ifstream ifs(DATA_DIR "/config/townsDefs.txt");
  154. int ccc;
  155. ifs>>ccc;
  156. for(int i=0;i<ccc*2;i++)
  157. {
  158. CGDefInfo *n;
  159. if(i<ccc)
  160. {
  161. n = CGI->state->villages[i];
  162. map->defy.push_back(CGI->state->forts[i]);
  163. }
  164. else
  165. n = CGI->state->capitols[i%ccc];
  166. ifs >> n->name;
  167. if(!n)
  168. tlog1 << "*HUGE* Warning - missing town def for " << i << std::endl;
  169. else
  170. map->defy.push_back(n);
  171. }
  172. }
  173. void CClient::endGame( bool closeConnection /*= true*/ )
  174. {
  175. // Game is ending
  176. // Tell the network thread to reach a stable state
  177. GH.curInt = NULL;
  178. LOCPLINT->terminate_cond.setn(true);
  179. LOCPLINT->pim->lock();
  180. tlog0 << "\n\nEnding current game!" << std::endl;
  181. if(GH.topInt())
  182. GH.topInt()->deactivate();
  183. GH.listInt.clear();
  184. GH.objsToBlit.clear();
  185. GH.statusbar = NULL;
  186. tlog0 << "Removed GUI." << std::endl;
  187. delete CGI->mh;
  188. CGI->mh = NULL;
  189. delete CGI->state;
  190. CGI->state = NULL;
  191. tlog0 << "Deleted mapHandler and gameState." << std::endl;
  192. CPlayerInterface * oldInt = LOCPLINT;
  193. LOCPLINT = NULL;
  194. oldInt->pim->unlock();
  195. while (!playerint.empty())
  196. {
  197. CGameInterface *pint = playerint.begin()->second;
  198. playerint.erase(playerint.begin());
  199. delete pint;
  200. }
  201. BOOST_FOREACH(CCallback *cb, callbacks)
  202. {
  203. delete cb;
  204. }
  205. tlog0 << "Deleted playerInts." << std::endl;
  206. if(closeConnection)
  207. stopConnection();
  208. tlog0 << "Client stopped." << std::endl;
  209. }
  210. void CClient::loadGame( const std::string & fname )
  211. {
  212. tlog0 <<"\n\nLoading procedure started!\n\n";
  213. CServerHandler sh;
  214. sh.startServer();
  215. timeHandler tmh;
  216. {
  217. char sig[8];
  218. CMapHeader dum;
  219. CGI->mh = new CMapHandler();
  220. StartInfo *si;
  221. CLoadFile lf(fname + ".vlgm1");
  222. lf >> sig >> dum >> si;
  223. tlog0 <<"Reading save signature: "<<tmh.getDif()<<std::endl;
  224. lf >> *VLC;
  225. CGI->setFromLib();
  226. tlog0 <<"Reading handlers: "<<tmh.getDif()<<std::endl;
  227. lf >> gs;
  228. tlog0 <<"Reading gamestate: "<<tmh.getDif()<<std::endl;
  229. CGI->state = gs;
  230. CGI->mh->map = gs->map;
  231. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  232. CGI->mh->init();
  233. initVillagesCapitols(gs->map);
  234. tlog0 <<"Initing maphandler: "<<tmh.getDif()<<std::endl;
  235. }
  236. serv = sh.connectToServer();
  237. serv->addStdVecItems(gs);
  238. tmh.update();
  239. ui8 pom8;
  240. *serv << ui8(3) << ui8(1); //load game; one client
  241. *serv << fname;
  242. *serv >> pom8;
  243. if(pom8)
  244. throw "Server cannot open the savegame!";
  245. else
  246. tlog0 << "Server opened savegame properly.\n";
  247. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  248. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  249. it != gs->scenarioOps->playerInfos.end(); ++it)
  250. {
  251. *serv << ui8(it->first); //players
  252. }
  253. *serv << ui8(255); // neutrals
  254. tlog0 <<"Sent info to server: "<<tmh.getDif()<<std::endl;
  255. {
  256. CLoadFile lf(fname + ".vcgm1");
  257. lf >> *this;
  258. }
  259. }
  260. int CClient::getCurrentPlayer()
  261. {
  262. return gs->currentPlayer;
  263. }
  264. int CClient::getSelectedHero()
  265. {
  266. if(const CGHeroInstance *selHero = IGameCallback::getSelectedHero(getCurrentPlayer()))
  267. return selHero->id;
  268. else
  269. return -1;
  270. }
  271. void CClient::newGame( CConnection *con, StartInfo *si )
  272. {
  273. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  274. std::set<ui8> myPlayers;
  275. if (con == NULL)
  276. {
  277. CServerHandler sh;
  278. serv = sh.connectToServer();
  279. }
  280. else
  281. {
  282. serv = con;
  283. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  284. }
  285. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  286. it != si->playerInfos.end(); ++it)
  287. {
  288. if(networkMode == SINGLE //single - one client has all player
  289. || networkMode != SINGLE && serv->connectionID == it->second.human //multi - client has only "its players"
  290. || networkMode == HOST && it->second.human == false) //multi - host has all AI players
  291. {
  292. myPlayers.insert(ui8(it->first)); //add player
  293. }
  294. }
  295. if(networkMode != GUEST)
  296. myPlayers.insert(255); //neutral
  297. timeHandler tmh;
  298. CGI->state = new CGameState();
  299. tlog0 <<"\tGamestate: "<<tmh.getDif()<<std::endl;
  300. CConnection &c(*serv);
  301. ////////////////////////////////////////////////////
  302. if(networkMode == SINGLE)
  303. {
  304. ui8 pom8;
  305. c << ui8(2) << ui8(1); //new game; one client
  306. c << *si;
  307. c >> pom8;
  308. if(pom8)
  309. throw "Server cannot open the map!";
  310. else
  311. tlog0 << "Server opened map properly.\n";
  312. }
  313. c << myPlayers;
  314. ui32 seed, sum;
  315. c >> si >> sum >> seed;
  316. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
  317. tlog0 << "\tUsing random seed: "<<seed << std::endl;
  318. gs = CGI->state;
  319. gs->scenarioOps = si;
  320. gs->init(si, sum, seed);
  321. CGI->mh = new CMapHandler();
  322. tlog0 <<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
  323. CGI->mh->map = gs->map;
  324. tlog0 <<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
  325. CGI->mh->init();
  326. initVillagesCapitols(gs->map);
  327. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  328. tlog0 <<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
  329. int humanPlayers = 0;
  330. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  331. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  332. {
  333. ui8 color = it->first;
  334. if(!vstd::contains(myPlayers, color))
  335. continue;
  336. CCallback *cb = new CCallback(gs,color,this);
  337. if(!it->second.human)
  338. {
  339. playerint[color] = static_cast<CGameInterface*>(CAIHandler::getNewAI(cb,conf.cc.defaultAI));
  340. }
  341. else
  342. {
  343. playerint[color] = new CPlayerInterface(color);
  344. humanPlayers++;
  345. }
  346. gs->currentPlayer = color;
  347. playerint[color]->init(cb);
  348. }
  349. serv->addStdVecItems(CGI->state);
  350. hotSeat = (humanPlayers > 1);
  351. playerint[255] = CAIHandler::getNewAI(cb,conf.cc.defaultAI);
  352. playerint[255]->init(new CCallback(gs,255,this));
  353. }
  354. template <typename Handler>
  355. void CClient::serialize( Handler &h, const int version )
  356. {
  357. h & hotSeat;
  358. if(h.saving)
  359. {
  360. ui8 players = playerint.size();
  361. h & players;
  362. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  363. {
  364. h & i->first & i->second->dllName;
  365. i->second->serialize(h,version);
  366. }
  367. }
  368. else
  369. {
  370. ui8 players;
  371. h & players;
  372. for(int i=0; i < players; i++)
  373. {
  374. std::string dllname;
  375. ui8 pid;
  376. h & pid & dllname;
  377. CCallback *callback = new CCallback(gs,pid,this);
  378. callbacks.insert(callback);
  379. CGameInterface *nInt = NULL;
  380. if(dllname.length())
  381. nInt = CAIHandler::getNewAI(callback,dllname);
  382. else
  383. nInt = new CPlayerInterface(pid);
  384. playerint[pid] = nInt;
  385. nInt->init(callback);
  386. nInt->serialize(h, version);
  387. }
  388. }
  389. }
  390. void CClient::handlePack( CPack * pack )
  391. {
  392. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  393. if(apply)
  394. {
  395. apply->applyOnClBefore(this,pack);
  396. tlog5 << "\tMade first apply on cl\n";
  397. gs->apply(pack);
  398. tlog5 << "\tApplied on gs\n";
  399. apply->applyOnClAfter(this,pack);
  400. tlog5 << "\tMade second apply on cl\n";
  401. }
  402. else
  403. {
  404. tlog1 << "Message cannot be applied, cannot find applier!\n";
  405. }
  406. delete pack;
  407. }
  408. void CClient::updatePaths()
  409. {
  410. const CGHeroInstance *h = getHero(getSelectedHero());
  411. if (h)//if we have selected hero...
  412. gs->calculatePaths(h, *pathInfo);
  413. }
  414. void CClient::finishCampaign( CCampaignState * camp )
  415. {
  416. }
  417. void CClient::proposeNextMission( CCampaignState * camp )
  418. {
  419. GH.pushInt(new CBonusSelection(camp));
  420. GH.curInt = CGP;
  421. }
  422. void CClient::stopConnection()
  423. {
  424. terminate = true;
  425. if (serv) //request closing connection
  426. {
  427. tlog0 << "Connection has been requested to be closed.\n";
  428. boost::unique_lock<boost::mutex>(*serv->wmx);
  429. *serv << &CloseServer();
  430. tlog0 << "Sent closing signal to the server\n";
  431. }
  432. if(connectionHandler)//end connection handler
  433. {
  434. if(connectionHandler->get_id() != boost::this_thread::get_id())
  435. connectionHandler->join();
  436. tlog0 << "Connection handler thread joined" << std::endl;
  437. delete connectionHandler;
  438. connectionHandler = NULL;
  439. }
  440. if (serv) //and delete connection
  441. {
  442. serv->close();
  443. delete serv;
  444. serv = NULL;
  445. tlog3 << "Our socket has been closed." << std::endl;
  446. }
  447. }
  448. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  449. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  450. void CServerHandler::startServer()
  451. {
  452. th.update();
  453. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable; //TODO: will it work on non-windows platforms?
  454. if(verbose)
  455. tlog0 << "Setting up thread calling server: " << th.getDif() << std::endl;
  456. }
  457. void CServerHandler::waitForServer()
  458. {
  459. if(!serverThread)
  460. startServer();
  461. th.update();
  462. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  463. while(!shared->sr->ready)
  464. {
  465. shared->sr->cond.wait(slock);
  466. }
  467. if(verbose)
  468. tlog0 << "Waiting for server: " << th.getDif() << std::endl;
  469. }
  470. CConnection * CServerHandler::connectToServer()
  471. {
  472. if(!shared->sr->ready)
  473. waitForServer();
  474. th.update();
  475. CConnection *ret = justConnectToServer(conf.cc.server, port);
  476. if(verbose)
  477. tlog0<<"\tConnecting to the server: "<<th.getDif()<<std::endl;
  478. return ret;
  479. }
  480. CServerHandler::CServerHandler(bool runServer /*= false*/)
  481. {
  482. serverThread = NULL;
  483. shared = NULL;
  484. port = boost::lexical_cast<std::string>(conf.cc.port);
  485. 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
  486. try
  487. {
  488. shared = new SharedMem();
  489. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  490. }
  491. CServerHandler::~CServerHandler()
  492. {
  493. delete shared;
  494. delete serverThread; //detaches, not kills thread
  495. }
  496. void CServerHandler::callServer()
  497. {
  498. std::string comm = std::string(BIN_DIR PATH_SEPARATOR SERVER_NAME " ") + port + " > server_log.txt";
  499. std::system(comm.c_str());
  500. tlog0 << "Server finished\n";
  501. }
  502. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  503. {
  504. CConnection *ret = NULL;
  505. while(!ret)
  506. {
  507. try
  508. {
  509. tlog0 << "Establishing connection...\n";
  510. ret = new CConnection( host.size() ? host : conf.cc.server,
  511. port.size() ? port : boost::lexical_cast<std::string>(conf.cc.port),
  512. NAME);
  513. }
  514. catch(...)
  515. {
  516. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  517. SDL_Delay(2000);
  518. }
  519. }
  520. return ret;
  521. }