EntryPoint.cpp 16 KB

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