EntryPoint.cpp 16 KB

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