CMT.cpp 15 KB

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