EntryPoint.cpp 15 KB

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