Client.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. LOCPLINT = NULL;
  193. while (!playerint.empty())
  194. {
  195. CGameInterface *pint = playerint.begin()->second;
  196. playerint.erase(playerint.begin());
  197. delete pint;
  198. }
  199. BOOST_FOREACH(CCallback *cb, callbacks)
  200. {
  201. delete cb;
  202. }
  203. tlog0 << "Deleted playerInts." << std::endl;
  204. if(closeConnection)
  205. stopConnection();
  206. tlog0 << "Client stopped." << std::endl;
  207. }
  208. void CClient::loadGame( const std::string & fname )
  209. {
  210. tlog0 <<"\n\nLoading procedure started!\n\n";
  211. CServerHandler sh;
  212. sh.startServer();
  213. timeHandler tmh;
  214. {
  215. char sig[8];
  216. CMapHeader dum;
  217. CGI->mh = new CMapHandler();
  218. StartInfo *si;
  219. CLoadFile lf(fname + ".vlgm1");
  220. lf >> sig >> dum >> si;
  221. tlog0 <<"Reading save signature: "<<tmh.getDif()<<std::endl;
  222. lf >> *VLC;
  223. CGI->setFromLib();
  224. tlog0 <<"Reading handlers: "<<tmh.getDif()<<std::endl;
  225. lf >> gs;
  226. tlog0 <<"Reading gamestate: "<<tmh.getDif()<<std::endl;
  227. CGI->state = gs;
  228. CGI->mh->map = gs->map;
  229. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  230. CGI->mh->init();
  231. initVillagesCapitols(gs->map);
  232. tlog0 <<"Initing maphandler: "<<tmh.getDif()<<std::endl;
  233. }
  234. serv = sh.connectToServer();
  235. serv->addStdVecItems(gs);
  236. tmh.update();
  237. ui8 pom8;
  238. *serv << ui8(3) << ui8(1); //load game; one client
  239. *serv << fname;
  240. *serv >> pom8;
  241. if(pom8)
  242. throw "Server cannot open the savegame!";
  243. else
  244. tlog0 << "Server opened savegame properly.\n";
  245. *serv << ui32(gs->scenarioOps->playerInfos.size()+1); //number of players + neutral
  246. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  247. it != gs->scenarioOps->playerInfos.end(); ++it)
  248. {
  249. *serv << ui8(it->first); //players
  250. }
  251. *serv << ui8(255); // neutrals
  252. tlog0 <<"Sent info to server: "<<tmh.getDif()<<std::endl;
  253. {
  254. CLoadFile lf(fname + ".vcgm1");
  255. lf >> *this;
  256. }
  257. }
  258. int CClient::getCurrentPlayer()
  259. {
  260. return gs->currentPlayer;
  261. }
  262. int CClient::getSelectedHero()
  263. {
  264. if(const CGHeroInstance *selHero = IGameCallback::getSelectedHero(getCurrentPlayer()))
  265. return selHero->id;
  266. else
  267. return -1;
  268. }
  269. void CClient::newGame( CConnection *con, StartInfo *si )
  270. {
  271. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  272. std::set<ui8> myPlayers;
  273. if (con == NULL)
  274. {
  275. CServerHandler sh;
  276. serv = sh.connectToServer();
  277. }
  278. else
  279. {
  280. serv = con;
  281. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  282. }
  283. for(std::map<int, PlayerSettings>::iterator it =si->playerInfos.begin();
  284. it != si->playerInfos.end(); ++it)
  285. {
  286. if(networkMode == SINGLE //single - one client has all player
  287. || networkMode != SINGLE && serv->connectionID == it->second.human //multi - client has only "its players"
  288. || networkMode == HOST && it->second.human == false) //multi - host has all AI players
  289. {
  290. myPlayers.insert(ui8(it->first)); //add player
  291. }
  292. }
  293. if(networkMode != GUEST)
  294. myPlayers.insert(255); //neutral
  295. timeHandler tmh;
  296. CGI->state = new CGameState();
  297. tlog0 <<"\tGamestate: "<<tmh.getDif()<<std::endl;
  298. CConnection &c(*serv);
  299. ////////////////////////////////////////////////////
  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)
  307. throw "Server cannot open the map!";
  308. else
  309. tlog0 << "Server opened map properly.\n";
  310. }
  311. c << myPlayers;
  312. ui32 seed, sum;
  313. c >> si >> sum >> seed;
  314. tlog0 <<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
  315. tlog0 << "\tUsing random seed: "<<seed << std::endl;
  316. gs = CGI->state;
  317. gs->scenarioOps = si;
  318. gs->init(si, sum, seed);
  319. CGI->mh = new CMapHandler();
  320. tlog0 <<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
  321. CGI->mh->map = gs->map;
  322. tlog0 <<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
  323. CGI->mh->init();
  324. initVillagesCapitols(gs->map);
  325. pathInfo = new CPathsInfo(int3(gs->map->width, gs->map->height, gs->map->twoLevel+1));
  326. tlog0 <<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
  327. int humanPlayers = 0;
  328. for(std::map<int, PlayerSettings>::iterator it = gs->scenarioOps->playerInfos.begin();
  329. it != gs->scenarioOps->playerInfos.end(); ++it)//initializing interfaces for players
  330. {
  331. ui8 color = it->first;
  332. if(!vstd::contains(myPlayers, color))
  333. continue;
  334. CCallback *cb = new CCallback(gs,color,this);
  335. if(!it->second.human)
  336. {
  337. playerint[color] = static_cast<CGameInterface*>(CAIHandler::getNewAI(cb,conf.cc.defaultAI));
  338. }
  339. else
  340. {
  341. playerint[color] = new CPlayerInterface(color);
  342. humanPlayers++;
  343. }
  344. gs->currentPlayer = color;
  345. playerint[color]->init(cb);
  346. }
  347. serv->addStdVecItems(CGI->state);
  348. hotSeat = (humanPlayers > 1);
  349. playerint[255] = CAIHandler::getNewAI(cb,conf.cc.defaultAI);
  350. playerint[255]->init(new CCallback(gs,255,this));
  351. }
  352. template <typename Handler>
  353. void CClient::serialize( Handler &h, const int version )
  354. {
  355. h & hotSeat;
  356. if(h.saving)
  357. {
  358. ui8 players = playerint.size();
  359. h & players;
  360. for(std::map<ui8,CGameInterface *>::iterator i = playerint.begin(); i != playerint.end(); i++)
  361. {
  362. h & i->first & i->second->dllName;
  363. i->second->serialize(h,version);
  364. }
  365. }
  366. else
  367. {
  368. ui8 players;
  369. h & players;
  370. for(int i=0; i < players; i++)
  371. {
  372. std::string dllname;
  373. ui8 pid;
  374. h & pid & dllname;
  375. CCallback *callback = new CCallback(gs,pid,this);
  376. callbacks.insert(callback);
  377. CGameInterface *nInt = NULL;
  378. if(dllname.length())
  379. nInt = CAIHandler::getNewAI(callback,dllname);
  380. else
  381. nInt = new CPlayerInterface(pid);
  382. playerint[pid] = nInt;
  383. nInt->init(callback);
  384. nInt->serialize(h, version);
  385. }
  386. }
  387. }
  388. void CClient::handlePack( CPack * pack )
  389. {
  390. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  391. if(apply)
  392. {
  393. apply->applyOnClBefore(this,pack);
  394. tlog5 << "\tMade first apply on cl\n";
  395. gs->apply(pack);
  396. tlog5 << "\tApplied on gs\n";
  397. apply->applyOnClAfter(this,pack);
  398. tlog5 << "\tMade second apply on cl\n";
  399. }
  400. else
  401. {
  402. tlog1 << "Message cannot be applied, cannot find applier!\n";
  403. }
  404. delete pack;
  405. }
  406. void CClient::updatePaths()
  407. {
  408. const CGHeroInstance *h = getHero(getSelectedHero());
  409. if (h)//if we have selected hero...
  410. gs->calculatePaths(h, *pathInfo);
  411. }
  412. void CClient::finishCampaign( CCampaignState * camp )
  413. {
  414. }
  415. void CClient::proposeNextMission( CCampaignState * camp )
  416. {
  417. GH.pushInt(new CBonusSelection(camp));
  418. GH.curInt = CGP;
  419. }
  420. void CClient::stopConnection()
  421. {
  422. terminate = true;
  423. if (serv)
  424. {
  425. tlog0 << "Connection has been requested to be closed.\n";
  426. boost::unique_lock<boost::mutex>(*serv->wmx);
  427. *serv << &CloseServer();
  428. tlog0 << "Sent closing signal to the server\n";
  429. serv->close();
  430. delete serv;
  431. serv = NULL;
  432. tlog3 << "Our socket has been closed." << std::endl;
  433. }
  434. if(connectionHandler)
  435. {
  436. if(connectionHandler->get_id() != boost::this_thread::get_id())
  437. connectionHandler->join();
  438. tlog0 << "Connection handler thread joined" << std::endl;
  439. delete connectionHandler;
  440. connectionHandler = NULL;
  441. }
  442. }
  443. template void CClient::serialize( CISer<CLoadFile> &h, const int version );
  444. template void CClient::serialize( COSer<CSaveFile> &h, const int version );
  445. void CServerHandler::startServer()
  446. {
  447. th.update();
  448. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable; //TODO: will it work on non-windows platforms?
  449. if(verbose)
  450. tlog0 << "Setting up thread calling server: " << th.getDif() << std::endl;
  451. }
  452. void CServerHandler::waitForServer()
  453. {
  454. if(!serverThread)
  455. startServer();
  456. th.update();
  457. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  458. while(!shared->sr->ready)
  459. {
  460. shared->sr->cond.wait(slock);
  461. }
  462. if(verbose)
  463. tlog0 << "Waiting for server: " << th.getDif() << std::endl;
  464. }
  465. CConnection * CServerHandler::connectToServer()
  466. {
  467. if(!shared->sr->ready)
  468. waitForServer();
  469. th.update();
  470. CConnection *ret = justConnectToServer(conf.cc.server, port);
  471. if(verbose)
  472. tlog0<<"\tConnecting to the server: "<<th.getDif()<<std::endl;
  473. return ret;
  474. }
  475. CServerHandler::CServerHandler(bool runServer /*= false*/)
  476. {
  477. serverThread = NULL;
  478. shared = NULL;
  479. port = boost::lexical_cast<std::string>(conf.cc.port);
  480. 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
  481. try
  482. {
  483. shared = new SharedMem();
  484. } HANDLE_EXCEPTIONC(tlog1 << "Cannot open interprocess memory: ";)
  485. }
  486. CServerHandler::~CServerHandler()
  487. {
  488. delete shared;
  489. delete serverThread; //detaches, not kills thread
  490. }
  491. void CServerHandler::callServer()
  492. {
  493. std::string comm = std::string(BIN_DIR PATH_SEPARATOR SERVER_NAME " ") + port + " > server_log.txt";
  494. std::system(comm.c_str());
  495. tlog0 << "Server finished\n";
  496. }
  497. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  498. {
  499. CConnection *ret = NULL;
  500. while(!ret)
  501. {
  502. try
  503. {
  504. tlog0 << "Establishing connection...\n";
  505. ret = new CConnection( host.size() ? host : conf.cc.server,
  506. port.size() ? port : boost::lexical_cast<std::string>(conf.cc.port),
  507. NAME);
  508. }
  509. catch(...)
  510. {
  511. tlog1 << "\nCannot establish connection! Retrying within 2 seconds" << std::endl;
  512. SDL_Delay(2000);
  513. }
  514. }
  515. return ret;
  516. }