EntryPoint.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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/AssetGenerator.h"
  28. #include "../client/render/Graphics.h"
  29. #include "../client/render/IRenderHandler.h"
  30. #include "../client/render/IScreenHandler.h"
  31. #include "../client/lobby/CBonusSelection.h"
  32. #include "../client/windows/CMessage.h"
  33. #include "../client/windows/InfoWindows.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/VCMI_Lib.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. CGI->setFromLib();
  73. }
  74. catch (const DataLoadingException & e)
  75. {
  76. criticalInitializationError = e.what();
  77. return;
  78. }
  79. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  80. // Debug code to load all maps on start
  81. //ClientCommandManager commandController;
  82. //commandController.processCommand("convert txt", false);
  83. }
  84. static void checkForModLoadingFailure()
  85. {
  86. const auto & brokenMods = VLC->identifiersHandler->getModsWithFailedRequests();
  87. if (!brokenMods.empty())
  88. {
  89. MetaString messageText;
  90. messageText.appendTextID("vcmi.client.errors.modLoadingFailure");
  91. for (const auto & modID : brokenMods)
  92. {
  93. messageText.appendRawString(VLC->modh->getModInfo(modID).getName());
  94. messageText.appendEOL();
  95. }
  96. CInfoWindow::showInfoDialog(messageText.toString(), {});
  97. }
  98. }
  99. static void prog_version()
  100. {
  101. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  102. std::cout << VCMIDirs::get().genHelpString();
  103. }
  104. static void prog_help(const po::options_description &opts)
  105. {
  106. auto time = std::time(nullptr);
  107. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  108. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  109. printf("This is free software; see the source for copying conditions. There is NO\n");
  110. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  111. printf("\n");
  112. std::cout << opts;
  113. }
  114. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  115. int wmain(int argc, wchar_t* argv[])
  116. #elif defined(VCMI_MOBILE)
  117. int SDL_main(int argc, char *argv[])
  118. #else
  119. int main(int argc, char * argv[])
  120. #endif
  121. {
  122. #ifdef VCMI_ANDROID
  123. CAndroidVMHelper::initClassloader(SDL_AndroidGetJNIEnv());
  124. // boost will crash without this
  125. setenv("LANG", "C", 1);
  126. #endif
  127. #if !defined(VCMI_MOBILE)
  128. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  129. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  130. #endif
  131. std::cout << "Starting... " << std::endl;
  132. po::options_description opts("Allowed options");
  133. po::variables_map vm;
  134. opts.add_options()
  135. ("help,h", "display help and exit")
  136. ("version,v", "display version information and exit")
  137. ("testmap", po::value<std::string>(), "")
  138. ("testsave", po::value<std::string>(), "")
  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. #ifndef VCMI_IOS
  190. console = new CConsoleHandler();
  191. auto callbackFunction = [](std::string buffer, bool calledFromIngameConsole)
  192. {
  193. ClientCommandManager commandController;
  194. commandController.processCommand(buffer, calledFromIngameConsole);
  195. };
  196. *console->cb = callbackFunction;
  197. console->start();
  198. #endif
  199. setThreadNameLoggingOnly("MainGUI");
  200. const boost::filesystem::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  201. logConfig = new CBasicLogConfigurator(logPath, console);
  202. logConfig->configureDefault();
  203. logGlobal->info("Starting client of '%s'", GameConstants::VCMI_VERSION);
  204. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  205. logGlobal->info("The log file will be saved to %s", logPath);
  206. AssetGenerator::clear();
  207. // Init filesystem and settings
  208. try
  209. {
  210. preinitDLL(::console, false);
  211. }
  212. catch (const DataLoadingException & e)
  213. {
  214. handleFatalError(e.what(), true);
  215. }
  216. Settings session = settings.write["session"];
  217. auto setSettingBool = [&](std::string key, std::string arg) {
  218. Settings s = settings.write(vstd::split(key, "/"));
  219. if(vm.count(arg))
  220. s->Bool() = true;
  221. else if(s->isNull())
  222. s->Bool() = false;
  223. };
  224. auto setSettingInteger = [&](std::string key, std::string arg, si64 defaultValue) {
  225. Settings s = settings.write(vstd::split(key, "/"));
  226. if(vm.count(arg))
  227. s->Integer() = vm[arg].as<si64>();
  228. else if(s->isNull())
  229. s->Integer() = defaultValue;
  230. };
  231. setSettingBool("session/onlyai", "onlyAI");
  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. logConfig->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. if(!settings["session"]["headless"].Bool())
  269. GH.init();
  270. CCS = new CClientState();
  271. CGI = new CGameInfo(); //contains all global information about game (texts, lodHandlers, map handler etc.)
  272. CSH = new CServerHandler();
  273. // Initialize video
  274. #ifdef DISABLE_VIDEO
  275. CCS->videoh = new CEmptyVideoPlayer();
  276. #else
  277. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  278. CCS->videoh = new CVideoPlayer();
  279. else
  280. CCS->videoh = new CEmptyVideoPlayer();
  281. #endif
  282. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  283. if(!settings["session"]["headless"].Bool())
  284. {
  285. //initializing audio
  286. CCS->soundh = new CSoundHandler();
  287. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  288. CCS->musich = new CMusicHandler();
  289. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  290. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  291. }
  292. #ifndef VCMI_NO_THREADED_LOAD
  293. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  294. boost::thread loading([]()
  295. {
  296. setThreadName("initialize");
  297. init();
  298. });
  299. #else
  300. init();
  301. #endif
  302. #ifndef VCMI_NO_THREADED_LOAD
  303. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  304. {
  305. CAndroidVMHelper vmHelper;
  306. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  307. #endif // ANDROID
  308. loading.join();
  309. #ifdef VCMI_ANDROID
  310. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  311. }
  312. #endif // ANDROID
  313. #endif // THREADED
  314. if (criticalInitializationError.has_value())
  315. {
  316. handleFatalError(criticalInitializationError.value(), false);
  317. }
  318. if(!settings["session"]["headless"].Bool())
  319. {
  320. pomtime.getDiff();
  321. graphics = new Graphics(); // should be before curh
  322. GH.renderHandler().onLibraryLoadingFinished(CGI);
  323. CCS->curh = new CursorHandler();
  324. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  325. CMessage::init();
  326. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  327. CCS->curh->show();
  328. }
  329. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  330. session["autoSkip"].Bool() = vm.count("autoSkip");
  331. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  332. session["aiSolo"].Bool() = false;
  333. if(vm.count("testmap"))
  334. {
  335. session["testmap"].String() = vm["testmap"].as<std::string>();
  336. session["onlyai"].Bool() = true;
  337. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  338. }
  339. else if(vm.count("testsave"))
  340. {
  341. session["testsave"].String() = vm["testsave"].as<std::string>();
  342. session["onlyai"].Bool() = true;
  343. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  344. }
  345. else
  346. {
  347. auto mmenu = CMainMenu::create();
  348. GH.curInt = mmenu.get();
  349. bool playIntroVideo = !settings["session"]["headless"].Bool() && !vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool();
  350. if(playIntroVideo)
  351. mmenu->playIntroVideos();
  352. else
  353. mmenu->playMusic();
  354. }
  355. std::vector<std::string> names;
  356. if(!settings["session"]["headless"].Bool())
  357. {
  358. checkForModLoadingFailure();
  359. mainLoop();
  360. }
  361. else
  362. {
  363. while(!headlessQuit)
  364. boost::this_thread::sleep_for(boost::chrono::milliseconds(200));
  365. boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
  366. quitApplication();
  367. }
  368. return 0;
  369. }
  370. static void mainLoop()
  371. {
  372. #ifndef VCMI_UNIX
  373. // on Linux, name of main thread is also name of our process. Which we don't want to change
  374. setThreadName("MainGUI");
  375. #endif
  376. while(1) //main SDL events loop
  377. {
  378. GH.input().fetchEvents();
  379. GH.renderFrame();
  380. }
  381. }
  382. [[noreturn]] static void quitApplicationImmediately(int error_code)
  383. {
  384. // Perform quick exit without executing static destructors and let OS cleanup anything that we did not
  385. // We generally don't care about them and this leads to numerous issues, e.g.
  386. // destruction of locked mutexes (fails an assertion), even in third-party libraries (as well as native libs on Android)
  387. // Android - std::quick_exit is available only starting from API level 21
  388. // Mingw, macOS and iOS - std::quick_exit is unavailable (at least in current version of CI)
  389. #if (defined(__ANDROID_API__) && __ANDROID_API__ < 21) || (defined(__MINGW32__)) || defined(VCMI_APPLE)
  390. ::exit(error_code);
  391. #else
  392. std::quick_exit(error_code);
  393. #endif
  394. }
  395. [[noreturn]] static void quitApplication()
  396. {
  397. CSH->endNetwork();
  398. if(!settings["session"]["headless"].Bool())
  399. {
  400. if(CSH->client)
  401. CSH->endGameplay();
  402. GH.windows().clear();
  403. }
  404. vstd::clear_pointer(CSH);
  405. CMM.reset();
  406. if(!settings["session"]["headless"].Bool())
  407. {
  408. // cleanup, mostly to remove false leaks from analyzer
  409. if(CCS)
  410. {
  411. delete CCS->consoleh;
  412. delete CCS->curh;
  413. delete CCS->videoh;
  414. delete CCS->musich;
  415. delete CCS->soundh;
  416. vstd::clear_pointer(CCS);
  417. }
  418. CMessage::dispose();
  419. vstd::clear_pointer(graphics);
  420. }
  421. vstd::clear_pointer(VLC);
  422. // sometimes leads to a hang. TODO: investigate
  423. //vstd::clear_pointer(console);// should be removed after everything else since used by logging
  424. if(!settings["session"]["headless"].Bool())
  425. GH.screenHandler().close();
  426. if(logConfig != nullptr)
  427. {
  428. logConfig->deconfigure();
  429. delete logConfig;
  430. logConfig = nullptr;
  431. }
  432. std::cout << "Ending...\n";
  433. quitApplicationImmediately(0);
  434. }
  435. void handleQuit(bool ask)
  436. {
  437. if(!ask)
  438. {
  439. if(settings["session"]["headless"].Bool())
  440. {
  441. headlessQuit = true;
  442. }
  443. else
  444. {
  445. quitApplication();
  446. }
  447. return;
  448. }
  449. // FIXME: avoids crash if player attempts to close game while opening is still playing
  450. // use cursor handler as indicator that loading is not done yet
  451. // proper solution would be to abort init thread (or wait for it to finish)
  452. if (!CCS->curh)
  453. {
  454. quitApplicationImmediately(0);
  455. }
  456. if (LOCPLINT)
  457. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], quitApplication, nullptr);
  458. else
  459. CInfoWindow::showYesNoDialog(CGI->generaltexth->allTexts[69], {}, quitApplication, {}, PlayerColor(1));
  460. }
  461. /// Notify user about encountered fatal error and terminate the game
  462. /// TODO: decide on better location for this method
  463. void handleFatalError(const std::string & message, bool terminate)
  464. {
  465. logGlobal->error("FATAL ERROR ENCOUNTERED, VCMI WILL NOW TERMINATE");
  466. logGlobal->error("Reason: %s", message);
  467. std::string messageToShow = "Fatal error! " + message;
  468. SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal error!", messageToShow.c_str(), nullptr);
  469. if (terminate)
  470. throw std::runtime_error(message);
  471. else
  472. quitApplicationImmediately(1);
  473. }