CMT.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. // CMT.cpp : Defines the entry point for the console application.
  2. //
  3. #include "../stdafx.h"
  4. #include <cmath>
  5. #include <string>
  6. #include <vector>
  7. #include <queue>
  8. #include <cmath>
  9. #include <boost/algorithm/string.hpp>
  10. #include <boost/filesystem/operations.hpp>
  11. #include <boost/thread.hpp>
  12. #include <SDL_mixer.h>
  13. #include "SDL_Extensions.h"
  14. #include "SDL_framerate.h"
  15. #include "CGameInfo.h"
  16. #include "../mapHandler.h"
  17. #include "../global.h"
  18. #include "CPreGame.h"
  19. #include "CCastleInterface.h"
  20. #include "../CConsoleHandler.h"
  21. #include "CCursorHandler.h"
  22. #include "../lib/CGameState.h"
  23. #include "../CCallback.h"
  24. #include "CPlayerInterface.h"
  25. #include "CAdvmapInterface.h"
  26. #include "../hch/CBuildingHandler.h"
  27. #include "../hch/CVideoHandler.h"
  28. #include "../hch/CHeroHandler.h"
  29. #include "../hch/CCreatureHandler.h"
  30. #include "../hch/CSpellHandler.h"
  31. #include "../hch/CMusicHandler.h"
  32. #include "../hch/CVideoHandler.h"
  33. #include "../hch/CLodHandler.h"
  34. #include "../hch/CDefHandler.h"
  35. #include "../hch/CAmbarCendamo.h"
  36. #include "../hch/CGeneralTextHandler.h"
  37. #include "Graphics.h"
  38. #include "Client.h"
  39. #include "CConfigHandler.h"
  40. #include "../lib/Connection.h"
  41. #include "../lib/VCMI_Lib.h"
  42. #include "../lib/VCMIDirs.h"
  43. #include <cstdlib>
  44. #include "../lib/NetPacks.h"
  45. #ifdef _WIN32
  46. #include "SDL_syswm.h"
  47. #endif
  48. #if __MINGW32__
  49. #undef main
  50. #endif
  51. /*
  52. * CMT.cpp, part of VCMI engine
  53. *
  54. * Authors: listed in file AUTHORS in main folder
  55. *
  56. * License: GNU General Public License v2.0 or later
  57. * Full text of license available in license.txt file, in main folder
  58. *
  59. */
  60. std::string NAME_AFFIX = "client";
  61. std::string NAME = NAME_VER + std::string(" (") + NAME_AFFIX + ')'; //application name
  62. CGuiHandler GH;
  63. static CClient *client;
  64. SDL_Surface *screen = NULL, //main screen surface
  65. *screen2 = NULL,//and hlp surface (used to store not-active interfaces layer)
  66. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  67. static boost::thread *mainGUIThread;
  68. SystemOptions GDefaultOptions;
  69. VCMIDirs GVCMIDirs;
  70. std::queue<SDL_Event*> events;
  71. boost::mutex eventsM;
  72. static bool gOnlyAI = false;
  73. void processCommand(const std::string &message);
  74. static void setScreenRes(int w, int h, int bpp, bool fullscreen);
  75. void dispose();
  76. void playIntro();
  77. static void listenForEvents();
  78. void init()
  79. {
  80. timeHandler tmh, pomtime;
  81. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  82. int rmask = 0xff000000;int gmask = 0x00ff0000;int bmask = 0x0000ff00;int amask = 0x000000ff;
  83. #else
  84. int rmask = 0x000000ff; int gmask = 0x0000ff00; int bmask = 0x00ff0000; int amask = 0xff000000;
  85. #endif
  86. CSDL_Ext::std32bppSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, 1, 32, rmask, gmask, bmask, amask);
  87. tlog0 << "\tInitializing minors: " << pomtime.getDif() << std::endl;
  88. {
  89. //read system options
  90. CLoadFile settings(GVCMIDirs.UserPath + "/config/sysopts.bin");
  91. if(settings.sfile)
  92. {
  93. settings >> GDefaultOptions;
  94. }
  95. else //file not found (probably, may be also some kind of access problem
  96. {
  97. tlog2 << "Warning: Cannot read system options, default settings will be used.\n";
  98. //Try to create file
  99. tlog2 << "VCMI will try to save default system options...\n";
  100. GDefaultOptions.settingsChanged();
  101. }
  102. }
  103. THC tlog0<<"\tLoading default system settings: "<<pomtime.getDif()<<std::endl;
  104. //initializing audio
  105. // Note: because of interface button range, volume can only be a
  106. // multiple of 11, from 0 to 99.
  107. CGI->soundh = new CSoundHandler;
  108. CGI->soundh->init();
  109. CGI->soundh->setVolume(GDefaultOptions.soundVolume);
  110. CGI->musich = new CMusicHandler;
  111. //CGI->musich->init();
  112. //CGI->musich->setVolume(GDefaultOptions.musicVolume);
  113. tlog0<<"\tInitializing sound: "<<pomtime.getDif()<<std::endl;
  114. tlog0<<"Initializing screen and sound handling: "<<tmh.getDif()<<std::endl;
  115. initDLL(::console,logfile);
  116. CGI->setFromLib();
  117. CGI->soundh->initCreaturesSounds(CGI->creh->creatures);
  118. CGI->soundh->initSpellsSounds(CGI->spellh->spells);
  119. tlog0<<"Initializing VCMI_Lib: "<<tmh.getDif()<<std::endl;
  120. pomtime.getDif();
  121. CGI->curh = new CCursorHandler;
  122. CGI->curh->initCursor();
  123. CGI->curh->show();
  124. tlog0<<"Screen handler: "<<pomtime.getDif()<<std::endl;
  125. pomtime.getDif();
  126. graphics = new Graphics();
  127. graphics->loadHeroAnims();
  128. tlog0<<"\tMain graphics: "<<tmh.getDif()<<std::endl;
  129. tlog0<<"Initializing game graphics: "<<tmh.getDif()<<std::endl;
  130. CMessage::init();
  131. tlog0<<"Message handler: "<<tmh.getDif()<<std::endl;
  132. //CPG = new CPreGame(); //main menu and submenus
  133. //tlog0<<"Initialization CPreGame (together): "<<tmh.getDif()<<std::endl;
  134. }
  135. #ifndef __GNUC__
  136. int _tmain(int argc, _TCHAR* argv[])
  137. #else
  138. int main(int argc, char** argv)
  139. #endif
  140. {
  141. //Set environment vars to make window centered. Sometimes work, sometimes not. :/
  142. putenv("SDL_VIDEO_WINDOW_POS");
  143. putenv("SDL_VIDEO_CENTERED=1");
  144. tlog0 << "Starting... " << std::endl;
  145. timeHandler total, pomtime;
  146. std::cout.flags(std::ios::unitbuf);
  147. logfile = new std::ofstream("VCMI_Client_log.txt");
  148. console = new CConsoleHandler;
  149. *console->cb = boost::bind(&processCommand, _1);
  150. console->start();
  151. atexit(dispose);
  152. tlog0 <<"Creating console and logfile: "<<pomtime.getDif() << std::endl;
  153. conf.init();
  154. tlog0 <<"Loading settings: "<<pomtime.getDif() << std::endl;
  155. tlog0 << NAME << std::endl;
  156. srand ( time(NULL) );
  157. //CPG=NULL;
  158. CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler itp.)
  159. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
  160. {
  161. tlog1<<"Something was wrong: "<< SDL_GetError() << std::endl;
  162. exit(-1);
  163. }
  164. atexit(SDL_Quit);
  165. setScreenRes(800,600,conf.cc.bpp,conf.cc.fullscreen);
  166. tlog0 <<"\tInitializing screen: "<<pomtime.getDif() << std::endl;
  167. // Initialize video
  168. CGI->videoh = new CVideoPlayer;
  169. tlog0<<"\tInitializing video: "<<pomtime.getDif()<<std::endl;
  170. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  171. boost::thread loading(init);
  172. playIntro();
  173. SDL_FillRect(screen,NULL,0);
  174. SDL_Flip(screen);
  175. SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
  176. loading.join();
  177. tlog0<<"Initialization of VCMI (together): "<<total.getDif()<<std::endl;
  178. CGI->musich->playMusic(musicBase::mainMenu, -1);
  179. GH.curInt = new CGPreGame; //will set CGP pointer to itself
  180. mainGUIThread = new boost::thread(&CGuiHandler::run, boost::ref(GH));
  181. listenForEvents();
  182. return 0;
  183. }
  184. void processCommand(const std::string &message)
  185. {
  186. std::istringstream readed;
  187. readed.str(message);
  188. std::string cn; //command name
  189. readed >> cn;
  190. int3 src, dst;
  191. // int heronum;//TODO use me
  192. int3 dest;
  193. if(LOCPLINT && LOCPLINT->cingconsole)
  194. LOCPLINT->cingconsole->print(message);
  195. if(message==std::string("die, fool"))
  196. exit(EXIT_SUCCESS);
  197. else if(cn==std::string("activate"))
  198. {
  199. int what;
  200. readed >> what;
  201. switch (what)
  202. {
  203. case 0:
  204. GH.topInt()->activate();
  205. break;
  206. case 1:
  207. LOCPLINT->adventureInt->activate();
  208. break;
  209. case 2:
  210. LOCPLINT->castleInt->activate();
  211. break;
  212. }
  213. }
  214. else if(cn=="redraw")
  215. {
  216. GH.totalRedraw();
  217. }
  218. else if(cn=="screen")
  219. {
  220. tlog0 << "Screenbuf points to ";
  221. if(screenBuf == screen)
  222. tlog1 << "screen";
  223. else if(screenBuf == screen2)
  224. tlog1 << "screen2";
  225. else
  226. tlog1 << "?!?";
  227. tlog1 << std::endl;
  228. SDL_SaveBMP(screen, "Screen_c.bmp");
  229. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  230. }
  231. else if(cn=="save")
  232. {
  233. std::string fname;
  234. readed >> fname;
  235. client->save(fname);
  236. }
  237. //else if(cn=="list")
  238. //{
  239. // if(CPG)
  240. // for(int i = 0; i < CPG->ourScenSel->mapsel.ourGames.size(); i++)
  241. // tlog0 << i << ".\t" << CPG->ourScenSel->mapsel.ourGames[i]->filename << std::endl;
  242. //}
  243. else if(cn=="load")
  244. {
  245. // TODO: this code should end the running game and manage to call startGame instead
  246. std::string fname;
  247. readed >> fname;
  248. client->loadGame(fname);
  249. }
  250. //else if(cn=="ln")
  251. //{
  252. // int num;
  253. // readed >> num;
  254. // std::string &name = CPG->ourScenSel->mapsel.ourGames[num]->filename;
  255. // client->load(name.substr(0, name.size()-6));
  256. //}
  257. else if(cn=="resolution" || cn == "r")
  258. {
  259. if(LOCPLINT)
  260. {
  261. tlog1 << "Resolution can be set only before starting the game.\n";
  262. return;
  263. }
  264. std::map<std::pair<int,int>, config::GUIOptions >::iterator j;
  265. int i=1, hlp=1;
  266. tlog4 << "Available screen resolutions:\n";
  267. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end(); j++)
  268. tlog4 << i++ <<". " << j->first.first << " x " << j->first.second << std::endl;
  269. tlog4 << "Type number from 1 to " << i-1 << " to set appropriate resolution or 0 to cancel.\n";
  270. std::cin >> i;
  271. if(i < 0 || i > conf.guiOptions.size() || std::cin.bad() || std::cin.fail())
  272. {
  273. std::cin.clear();
  274. tlog1 << "Invalid resolution ID! Not a number between 0 and " << conf.guiOptions.size() << ". No settings changed.\n";
  275. }
  276. else if(!i)
  277. {
  278. return;
  279. }
  280. else
  281. {
  282. for(j=conf.guiOptions.begin(); j!=conf.guiOptions.end() && hlp++<i; j++); //move j to the i-th resolution info
  283. conf.cc.resx = j->first.first;
  284. conf.cc.resy = j->first.second;
  285. tlog0 << "Screen resolution set to " << conf.cc.resx << " x " << conf.cc.resy <<". It will be aplied when the game starts.\n";
  286. }
  287. }
  288. else if(message=="get txt")
  289. {
  290. boost::filesystem::create_directory("Extracted_txts");
  291. tlog0<<"Command accepted. Opening .lod file...\t";
  292. CLodHandler * txth = new CLodHandler;
  293. txth->init(std::string(DATA_DIR "/Data/H3bitmap.lod"),"");
  294. tlog0<<"done.\nScanning .lod file\n";
  295. int curp=0;
  296. std::string pattern = ".TXT", pom;
  297. for(int i=0;i<txth->entries.size(); i++)
  298. {
  299. pom = txth->entries[i].nameStr;
  300. if(boost::algorithm::find_last(pom,pattern))
  301. {
  302. txth->extractFile(std::string(DATA_DIR "/Extracted_txts/")+pom,pom);
  303. }
  304. if(i%8) continue;
  305. int p2 = ((float)i/(float)txth->entries.size())*(float)100;
  306. if(p2!=curp)
  307. {
  308. curp = p2;
  309. tlog0<<"\r"<<curp<<"%";
  310. }
  311. }
  312. tlog0<<"\rExtracting done :)\n";
  313. }
  314. else if(cn=="crash")
  315. {
  316. int *ptr = NULL;
  317. *ptr = 666;
  318. //disaster!
  319. }
  320. else if(cn == "onlyai")
  321. {
  322. gOnlyAI = true;
  323. }
  324. else if(client && client->serv && client->serv->connected) //send to server
  325. {
  326. PlayerMessage pm(LOCPLINT->playerID,message);
  327. *client->serv << &pm;
  328. }
  329. }
  330. //plays intro, ends when intro is over or button has been pressed (handles events)
  331. void playIntro()
  332. {
  333. if(CGI->videoh->openAndPlayVideo("3DOLOGO.SMK", 60, 40, screen, true))
  334. {
  335. CGI->videoh->openAndPlayVideo("AZVS.SMK", 60, 80, screen, true);
  336. }
  337. }
  338. void dispose()
  339. {
  340. delete logfile;
  341. if (console)
  342. delete console;
  343. }
  344. static void setScreenRes(int w, int h, int bpp, bool fullscreen)
  345. {
  346. // VCMI will only work with 3 or 4 bytes per pixel
  347. if (bpp < 24) bpp = 24;
  348. if (bpp > 32) bpp = 32;
  349. // Try to use the best screen depth for the display
  350. int suggestedBpp = SDL_VideoModeOK(w, h, bpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0));
  351. if(suggestedBpp == 0)
  352. {
  353. tlog1 << "Error: SDL says that " << w << "x" << h << " resolution is not available!\n";
  354. return;
  355. }
  356. bool bufOnScreen = (screenBuf == screen);
  357. if(suggestedBpp != bpp)
  358. {
  359. tlog2 << "Warning: SDL says that " << bpp << "bpp is wrong and suggests " << suggestedBpp << std::endl;
  360. }
  361. if(screen) //screen has been already initialized
  362. SDL_QuitSubSystem(SDL_INIT_VIDEO);
  363. SDL_InitSubSystem(SDL_INIT_VIDEO);
  364. if((screen = SDL_SetVideoMode(w, h, suggestedBpp, SDL_SWSURFACE|(fullscreen?SDL_FULLSCREEN:0))) == NULL)
  365. {
  366. tlog1 << "Requested screen resolution is not available (" << w << "x" << h << "x" << suggestedBpp << "bpp)\n";
  367. throw "Requested screen resolution is not available\n";
  368. }
  369. tlog0 << "New screen flags: " << screen->flags << std::endl;
  370. if(screen2)
  371. SDL_FreeSurface(screen2);
  372. screen2 = CSDL_Ext::copySurface(screen);
  373. SDL_EnableUNICODE(1);
  374. SDL_WM_SetCaption(NAME.c_str(),""); //set window title
  375. SDL_ShowCursor(SDL_DISABLE);
  376. #ifdef _WIN32
  377. SDL_SysWMinfo wm;
  378. SDL_VERSION(&wm.version);
  379. int getwm = SDL_GetWMInfo(&wm);
  380. if(getwm == 1)
  381. {
  382. int sw = GetSystemMetrics(SM_CXSCREEN),
  383. sh = GetSystemMetrics(SM_CYSCREEN);
  384. RECT curpos;
  385. GetWindowRect(wm.window,&curpos);
  386. int ourw = curpos.right - curpos.left,
  387. ourh = curpos.bottom - curpos.top;
  388. SetWindowPos(wm.window, 0, (sw - ourw)/2, (sh - ourh)/2, 0, 0, SWP_NOZORDER|SWP_NOSIZE);
  389. }
  390. else
  391. {
  392. tlog3 << "Something went wrong, getwm=" << getwm << std::endl;
  393. tlog3 << "SDL says: " << SDL_GetError() << std::endl;
  394. tlog3 << "Window won't be centered.\n";
  395. }
  396. #endif
  397. //TODO: centering game window on other platforms (or does the environment do their job correctly there?)
  398. screenBuf = bufOnScreen ? screen : screen2;
  399. }
  400. static void listenForEvents()
  401. {
  402. while(1) //main SDL events loop
  403. {
  404. SDL_Event *ev = new SDL_Event();
  405. //tlog0 << "Waiting... ";
  406. int ret = SDL_WaitEvent(ev);
  407. //tlog0 << "got " << (int)ev->type;
  408. if (ret == 0 || (ev->type==SDL_QUIT) ||
  409. (ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4 && (ev->key.keysym.mod & KMOD_ALT)))
  410. {
  411. if (client)
  412. client->stop();
  413. if (mainGUIThread)
  414. {
  415. GH.terminate = true;
  416. mainGUIThread->join();
  417. delete mainGUIThread;
  418. mainGUIThread = NULL;
  419. }
  420. delete console;
  421. console = NULL;
  422. SDL_Delay(750);
  423. SDL_Quit();
  424. tlog0 << "Ending...\n";
  425. break;
  426. }
  427. else if(LOCPLINT && ev->type == SDL_KEYDOWN && ev->key.keysym.sym==SDLK_F4)
  428. {
  429. boost::unique_lock<boost::recursive_mutex> lock(*LOCPLINT->pim);
  430. bool full = !(screen->flags&SDL_FULLSCREEN);
  431. setScreenRes(conf.cc.resx,conf.cc.resy,conf.cc.bpp,full);
  432. GH.totalRedraw();
  433. delete ev;
  434. continue;
  435. }
  436. else if(ev->type == SDL_USEREVENT && ev->user.code == 1)
  437. {
  438. setScreenRes(conf.cc.resx,conf.cc.resy,conf.cc.bpp,conf.cc.fullscreen);
  439. delete ev;
  440. continue;
  441. }
  442. else if (ev->type == SDL_USEREVENT && ev->user.code == 2) //something want to quit to main menu
  443. {
  444. client->stop();
  445. delete client;
  446. client = NULL;
  447. delete ev;
  448. GH.curInt = CGP;
  449. continue;
  450. }
  451. //tlog0 << " pushing ";
  452. eventsM.lock();
  453. events.push(ev);
  454. eventsM.unlock();
  455. //tlog0 << " done\n";
  456. }
  457. }
  458. void startGame(StartInfo * options)
  459. {
  460. GH.curInt =NULL;
  461. if(gOnlyAI)
  462. {
  463. for (size_t i =0; i < options->playerInfos.size(); i++)
  464. {
  465. options->playerInfos[i].human = false;
  466. }
  467. }
  468. if(screen->w != conf.cc.resx || screen->h != conf.cc.resy)
  469. {
  470. //push special event to order event reading thread to change resolution
  471. SDL_Event ev;
  472. ev.type = SDL_USEREVENT;
  473. ev.user.code = 1;
  474. SDL_PushEvent(&ev);
  475. }
  476. client = new CClient;
  477. if(options->mode == 0) //new game
  478. {
  479. client->newGame(NULL, options);
  480. }
  481. else //load game
  482. {
  483. std::string fname = options->mapname;
  484. boost::algorithm::erase_last(fname,".vlgm1");
  485. client->loadGame(fname);
  486. }
  487. CGI->musich->stopMusic();
  488. client->connectionHandler = new boost::thread(&CClient::run, client);
  489. }