Client.cpp 13 KB

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