EntryPoint.cpp 15 KB

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