CMT.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /*
  2. * CMT.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. // CMT.cpp : Defines the entry point for the console application.
  11. #include "StdInc.h"
  12. #include "CMT.h"
  13. #include "CGameInfo.h"
  14. #include "mainmenu/CMainMenu.h"
  15. #include "gui/CursorHandler.h"
  16. #include "eventsSDL/InputHandler.h"
  17. #include "CPlayerInterface.h"
  18. #include "CVideoHandler.h"
  19. #include "CMusicHandler.h"
  20. #include "gui/CGuiHandler.h"
  21. #include "gui/WindowHandler.h"
  22. #include "CServerHandler.h"
  23. #include "ClientCommandManager.h"
  24. #include "windows/CMessage.h"
  25. #include "render/IScreenHandler.h"
  26. #include "render/Graphics.h"
  27. #include "../lib/CConfigHandler.h"
  28. #include "../lib/CGeneralTextHandler.h"
  29. #include "../lib/CThreadHelper.h"
  30. #include "../lib/VCMIDirs.h"
  31. #include "../lib/VCMI_Lib.h"
  32. #include "../lib/filesystem/Filesystem.h"
  33. #include "../lib/logging/CBasicLogConfigurator.h"
  34. #include <boost/program_options.hpp>
  35. #include <vstd/StringUtils.h>
  36. #include <SDL_main.h>
  37. #include <SDL.h>
  38. #ifdef VCMI_ANDROID
  39. #include "../lib/CAndroidVMHelper.h"
  40. #include <SDL_system.h>
  41. #endif
  42. #if __MINGW32__
  43. #undef main
  44. #endif
  45. namespace po = boost::program_options;
  46. namespace po_style = boost::program_options::command_line_style;
  47. static po::variables_map vm;
  48. #ifndef VCMI_IOS
  49. void processCommand(const std::string &message);
  50. #endif
  51. void playIntro();
  52. static void mainLoop();
  53. static CBasicLogConfigurator *logConfig;
  54. void init()
  55. {
  56. CStopWatch tmh;
  57. loadDLLClasses();
  58. const_cast<CGameInfo*>(CGI)->setFromLib();
  59. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  60. // Debug code to load all maps on start
  61. //ClientCommandManager commandController;
  62. //commandController.processCommand("convert txt", false);
  63. }
  64. static void prog_version()
  65. {
  66. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  67. std::cout << VCMIDirs::get().genHelpString();
  68. }
  69. static void prog_help(const po::options_description &opts)
  70. {
  71. auto time = std::time(0);
  72. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  73. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  74. printf("This is free software; see the source for copying conditions. There is NO\n");
  75. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  76. printf("\n");
  77. std::cout << opts;
  78. }
  79. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  80. int wmain(int argc, wchar_t* argv[])
  81. #elif defined(VCMI_MOBILE)
  82. int SDL_main(int argc, char *argv[])
  83. #else
  84. int main(int argc, char * argv[])
  85. #endif
  86. {
  87. #ifdef VCMI_ANDROID
  88. CAndroidVMHelper::initClassloader(SDL_AndroidGetJNIEnv());
  89. // boost will crash without this
  90. setenv("LANG", "C", 1);
  91. #endif
  92. #if !defined(VCMI_MOBILE)
  93. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  94. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  95. #endif
  96. std::cout << "Starting... " << std::endl;
  97. po::options_description opts("Allowed options");
  98. opts.add_options()
  99. ("help,h", "display help and exit")
  100. ("version,v", "display version information and exit")
  101. ("testmap", po::value<std::string>(), "")
  102. ("testsave", po::value<std::string>(), "")
  103. ("spectate,s", "enable spectator interface for AI-only games")
  104. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  105. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  106. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  107. ("spectate-skip-battle", "skip battles in spectator view")
  108. ("spectate-skip-battle-result", "skip battle result window")
  109. ("onlyAI", "allow one to run without human player, all players will be default AI")
  110. ("headless", "runs without GUI, implies --onlyAI")
  111. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  112. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  113. ("autoSkip", "automatically skip turns in GUI")
  114. ("disable-video", "disable video player")
  115. ("nointro,i", "skips intro movies")
  116. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  117. ("serverport", po::value<si64>(), "override port specified in config file")
  118. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days")
  119. ("lobby", "parameters address, port, uuid to connect ro remote lobby session")
  120. ("lobby-address", po::value<std::string>(), "address to remote lobby")
  121. ("lobby-port", po::value<ui16>(), "port to remote lobby")
  122. ("lobby-host", "if this client hosts session")
  123. ("lobby-uuid", po::value<std::string>(), "uuid to the server")
  124. ("lobby-connections", po::value<ui16>(), "connections of server")
  125. ("lobby-username", po::value<std::string>(), "player name")
  126. ("lobby-gamemode", po::value<ui16>(), "use 0 for new game and 1 for load game")
  127. ("uuid", po::value<std::string>(), "uuid for the client");
  128. if(argc > 1)
  129. {
  130. try
  131. {
  132. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  133. }
  134. catch(boost::program_options::error &e)
  135. {
  136. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  137. }
  138. }
  139. po::notify(vm);
  140. if(vm.count("help"))
  141. {
  142. prog_help(opts);
  143. #ifdef VCMI_IOS
  144. exit(0);
  145. #else
  146. return 0;
  147. #endif
  148. }
  149. if(vm.count("version"))
  150. {
  151. prog_version();
  152. #ifdef VCMI_IOS
  153. exit(0);
  154. #else
  155. return 0;
  156. #endif
  157. }
  158. // Init old logging system and new (temporary) logging system
  159. CStopWatch total, pomtime;
  160. std::cout.flags(std::ios::unitbuf);
  161. #ifndef VCMI_IOS
  162. console = new CConsoleHandler();
  163. auto callbackFunction = [](std::string buffer, bool calledFromIngameConsole)
  164. {
  165. ClientCommandManager commandController;
  166. commandController.processCommand(buffer, calledFromIngameConsole);
  167. };
  168. *console->cb = callbackFunction;
  169. console->start();
  170. #endif
  171. const boost::filesystem::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  172. logConfig = new CBasicLogConfigurator(logPath, console);
  173. logConfig->configureDefault();
  174. logGlobal->info("Starting client of '%s'", GameConstants::VCMI_VERSION);
  175. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  176. logGlobal->info("The log file will be saved to %s", logPath);
  177. // Init filesystem and settings
  178. preinitDLL(::console);
  179. Settings session = settings.write["session"];
  180. auto setSettingBool = [](std::string key, std::string arg) {
  181. Settings s = settings.write(vstd::split(key, "/"));
  182. if(::vm.count(arg))
  183. s->Bool() = true;
  184. else if(s->isNull())
  185. s->Bool() = false;
  186. };
  187. auto setSettingInteger = [](std::string key, std::string arg, si64 defaultValue) {
  188. Settings s = settings.write(vstd::split(key, "/"));
  189. if(::vm.count(arg))
  190. s->Integer() = ::vm[arg].as<si64>();
  191. else if(s->isNull())
  192. s->Integer() = defaultValue;
  193. };
  194. setSettingBool("session/onlyai", "onlyAI");
  195. if(vm.count("headless"))
  196. {
  197. session["headless"].Bool() = true;
  198. session["onlyai"].Bool() = true;
  199. }
  200. else if(vm.count("spectate"))
  201. {
  202. session["spectate"].Bool() = true;
  203. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  204. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  205. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  206. if(vm.count("spectate-hero-speed"))
  207. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  208. if(vm.count("spectate-battle-speed"))
  209. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  210. }
  211. // Server settings
  212. setSettingBool("session/donotstartserver", "donotstartserver");
  213. // Init special testing settings
  214. setSettingInteger("session/serverport", "serverport", 0);
  215. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  216. // Initialize logging based on settings
  217. logConfig->configure();
  218. logGlobal->debug("settings = %s", settings.toJsonNode().toJson());
  219. // Some basic data validation to produce better error messages in cases of incorrect install
  220. auto testFile = [](std::string filename, std::string message)
  221. {
  222. if (!CResourceHandler::get()->existsResource(ResourcePath(filename)))
  223. handleFatalError(message, false);
  224. };
  225. testFile("DATA/HELP.TXT", "VCMI requires Heroes III: Shadow of Death or Heroes III: Complete data files to run!");
  226. testFile("MODS/VCMI/MOD.JSON", "VCMI installation is corrupted! Built-in mod was not found!");
  227. testFile("DATA/PLAYERS.PAL", "Heroes III data files are missing or corruped! Please reinstall them.");
  228. testFile("SPRITES/DEFAULT.DEF", "Heroes III data files are missing or corruped! Please reinstall them.");
  229. testFile("DATA/TENTCOLR.TXT", "Heroes III: Restoration of Erathia (including HD Edition) data files are not supported!");
  230. srand ( (unsigned int)time(nullptr) );
  231. if(!settings["session"]["headless"].Bool())
  232. GH.init();
  233. CCS = new CClientState();
  234. CGI = new CGameInfo(); //contains all global informations about game (texts, lodHandlers, map handler etc.)
  235. CSH = new CServerHandler();
  236. // Initialize video
  237. #ifdef DISABLE_VIDEO
  238. CCS->videoh = new CEmptyVideoPlayer();
  239. #else
  240. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  241. CCS->videoh = new CVideoPlayer();
  242. else
  243. CCS->videoh = new CEmptyVideoPlayer();
  244. #endif
  245. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  246. if(!settings["session"]["headless"].Bool())
  247. {
  248. //initializing audio
  249. CCS->soundh = new CSoundHandler();
  250. CCS->soundh->init();
  251. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  252. CCS->musich = new CMusicHandler();
  253. CCS->musich->init();
  254. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  255. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  256. }
  257. #ifndef VCMI_NO_THREADED_LOAD
  258. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  259. boost::thread loading([]()
  260. {
  261. setThreadName("initialize");
  262. init();
  263. });
  264. #else
  265. init();
  266. #endif
  267. if(!settings["session"]["headless"].Bool())
  268. {
  269. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  270. playIntro();
  271. GH.screenHandler().clearScreen();
  272. }
  273. #ifndef VCMI_NO_THREADED_LOAD
  274. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  275. {
  276. CAndroidVMHelper vmHelper;
  277. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  278. #endif // ANDROID
  279. loading.join();
  280. #ifdef VCMI_ANDROID
  281. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  282. }
  283. #endif // ANDROID
  284. #endif // THREADED
  285. if(!settings["session"]["headless"].Bool())
  286. {
  287. pomtime.getDiff();
  288. graphics = new Graphics(); // should be before curh
  289. CCS->curh = new CursorHandler();
  290. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  291. CMessage::init();
  292. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  293. CCS->curh->show();
  294. }
  295. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  296. session["autoSkip"].Bool() = vm.count("autoSkip");
  297. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  298. session["aiSolo"].Bool() = false;
  299. std::shared_ptr<CMainMenu> mmenu;
  300. if(vm.count("testmap"))
  301. {
  302. session["testmap"].String() = vm["testmap"].as<std::string>();
  303. session["onlyai"].Bool() = true;
  304. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  305. }
  306. else if(vm.count("testsave"))
  307. {
  308. session["testsave"].String() = vm["testsave"].as<std::string>();
  309. session["onlyai"].Bool() = true;
  310. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  311. }
  312. else
  313. {
  314. mmenu = CMainMenu::create();
  315. GH.curInt = mmenu.get();
  316. }
  317. std::vector<std::string> names;
  318. session["lobby"].Bool() = false;
  319. if(vm.count("lobby"))
  320. {
  321. session["lobby"].Bool() = true;
  322. session["host"].Bool() = false;
  323. session["address"].String() = vm["lobby-address"].as<std::string>();
  324. if(vm.count("lobby-username"))
  325. session["username"].String() = vm["lobby-username"].as<std::string>();
  326. else
  327. session["username"].String() = settings["launcher"]["lobbyUsername"].String();
  328. if(vm.count("lobby-gamemode"))
  329. session["gamemode"].Integer() = vm["lobby-gamemode"].as<ui16>();
  330. else
  331. session["gamemode"].Integer() = 0;
  332. CSH->uuid = vm["uuid"].as<std::string>();
  333. session["port"].Integer() = vm["lobby-port"].as<ui16>();
  334. logGlobal->info("Remote lobby mode at %s:%d, uuid is %s", session["address"].String(), session["port"].Integer(), CSH->uuid);
  335. if(vm.count("lobby-host"))
  336. {
  337. session["host"].Bool() = true;
  338. session["hostConnections"].String() = std::to_string(vm["lobby-connections"].as<ui16>());
  339. session["hostUuid"].String() = vm["lobby-uuid"].as<std::string>();
  340. logGlobal->info("This client will host session, server uuid is %s", session["hostUuid"].String());
  341. }
  342. //we should not reconnect to previous game in online mode
  343. Settings saveSession = settings.write["server"]["reconnect"];
  344. saveSession->Bool() = false;
  345. //start lobby immediately
  346. names.push_back(session["username"].String());
  347. ESelectionScreen sscreen = session["gamemode"].Integer() == 0 ? ESelectionScreen::newGame : ESelectionScreen::loadGame;
  348. mmenu->openLobby(sscreen, session["host"].Bool(), &names, ELoadMode::MULTI);
  349. }
  350. // Restore remote session - start game immediately
  351. if(settings["server"]["reconnect"].Bool())
  352. {
  353. CSH->restoreLastSession();
  354. }
  355. if(!settings["session"]["headless"].Bool())
  356. {
  357. mainLoop();
  358. }
  359. else
  360. {
  361. while(true)
  362. boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
  363. }
  364. return 0;
  365. }
  366. //plays intro, ends when intro is over or button has been pressed (handles events)
  367. void playIntro()
  368. {
  369. auto audioData = CCS->videoh->getAudio(VideoPath::builtin("3DOLOGO.SMK"));
  370. int sound = CCS->soundh->playSound(audioData);
  371. if(CCS->videoh->openAndPlayVideo(VideoPath::builtin("3DOLOGO.SMK"), 0, 1, true, true))
  372. {
  373. audioData = CCS->videoh->getAudio(VideoPath::builtin("NWCLOGO.SMK"));
  374. sound = CCS->soundh->playSound(audioData);
  375. if (CCS->videoh->openAndPlayVideo(VideoPath::builtin("NWCLOGO.SMK"), 0, 1, true, true))
  376. {
  377. audioData = CCS->videoh->getAudio(VideoPath::builtin("H3INTRO.SMK"));
  378. sound = CCS->soundh->playSound(audioData);
  379. CCS->videoh->openAndPlayVideo(VideoPath::builtin("H3INTRO.SMK"), 0, 1, true, true);
  380. }
  381. }
  382. CCS->soundh->stopSound(sound);
  383. }
  384. static void mainLoop()
  385. {
  386. setThreadName("MainGUI");
  387. while(1) //main SDL events loop
  388. {
  389. GH.input().fetchEvents();
  390. CSH->applyPacksOnLobbyScreen();
  391. GH.renderFrame();
  392. }
  393. }
  394. static void quitApplication()
  395. {
  396. if(!settings["session"]["headless"].Bool())
  397. {
  398. if(CSH->client)
  399. CSH->endGameplay();
  400. }
  401. GH.windows().clear();
  402. CMM.reset();
  403. if(!settings["session"]["headless"].Bool())
  404. {
  405. // cleanup, mostly to remove false leaks from analyzer
  406. if(CCS)
  407. {
  408. CCS->musich->release();
  409. CCS->soundh->release();
  410. vstd::clear_pointer(CCS);
  411. }
  412. CMessage::dispose();
  413. vstd::clear_pointer(graphics);
  414. }
  415. vstd::clear_pointer(VLC);
  416. vstd::clear_pointer(console);// should be removed after everything else since used by logging
  417. if(!settings["session"]["headless"].Bool())
  418. GH.screenHandler().close();
  419. if(logConfig != nullptr)
  420. {
  421. logConfig->deconfigure();
  422. delete logConfig;
  423. logConfig = nullptr;
  424. }
  425. std::cout << "Ending...\n";
  426. // this method is always called from event/network threads, which keep interface mutex locked
  427. // unlock it here to avoid assertion failure on GH destruction in exit()
  428. GH.interfaceMutex.unlock();
  429. exit(0);
  430. }
  431. void handleQuit(bool ask)
  432. {
  433. if(CSH->client && LOCPLINT && ask)
  434. {
  435. CCS->curh->set(Cursor::Map::POINTER);
  436. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], quitApplication, nullptr);
  437. }
  438. else
  439. {
  440. quitApplication();
  441. }
  442. }
  443. void handleFatalError(const std::string & message, bool terminate)
  444. {
  445. logGlobal->error("FATAL ERROR ENCOUTERED, VCMI WILL NOW TERMINATE");
  446. logGlobal->error("Reason: %s", message);
  447. std::string messageToShow = "Fatal error! " + message;
  448. SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal error!", messageToShow.c_str(), nullptr);
  449. if (terminate)
  450. throw std::runtime_error(message);
  451. else
  452. exit(1);
  453. }