LCOV - code coverage report
Current view: top level - source/ps/GameSetup - GameSetup.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 9 344 2.6 %
Date: 2026-12-03 01:19:39 Functions: 1 23 4.3 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "GameSetup.h"
      21             : 
      22             : #include "graphics/GameView.h"
      23             : #include "gui/CGUI.h"
      24             : #include "gui/GUIManager.h"
      25             : #include "gui/Scripting/JSInterface_GUIManager.h"
      26             : #include "i18n/L10n.h"
      27             : #include "lib/app_hooks.h"
      28             : #include "lib/code_annotation.h"
      29             : #include "lib/code_generation.h"
      30             : #include "lib/config2.h"
      31             : #include "lib/debug.h"
      32             : #include "lib/external_libraries/curl.h"
      33             : #include "lib/file/common/file_stats.h"
      34             : #include "lib/file/file_system.h"
      35             : #include "lib/file/vfs/vfs.h"
      36             : #include "lib/file/vfs/vfs_path.h"
      37             : #include "lib/file/vfs/vfs_util.h"
      38             : #include "lib/path.h"
      39             : #include "lib/status.h"
      40             : #include "lib/sysdep/os.h"
      41             : #include "lobby/XmppClient.h"
      42             : #include "network/NetClient.h"
      43             : #include "network/NetHost.h"
      44             : #include "network/NetMessage.h"
      45             : #include "network/NetServer.h"
      46             : #include "network/scripting/JSInterface_Network.h"
      47             : #include "ps/CConsole.h"
      48             : #include "ps/CLogger.h"
      49             : #include "ps/ConfigDB.h"
      50             : #include "ps/Errors.h"
      51             : #include "ps/Filesystem.h"
      52             : #include "ps/Game.h"
      53             : #include "ps/GameSetup/CmdLineArgs.h"
      54             : #include "ps/GameSetup/Config.h"
      55             : #include "ps/GameSetup/HWDetect.h"
      56             : #include "ps/GameSetup/Paths.h"
      57             : #include "ps/Globals.h"
      58             : #include "ps/Hotkey.h"
      59             : #include "ps/Joystick.h"
      60             : #include "ps/Loader.h"
      61             : #include "ps/Mod.h"
      62             : #include "ps/ModIo.h"
      63             : #include "ps/Profile.h"
      64             : #include "ps/ProfileViewer.h"
      65             : #include "ps/Profiler2.h"
      66             : #include "ps/Pyrogenesis.h"   // psSetLogDir
      67             : #include "ps/TemplateLoader.h"
      68             : #include "ps/ThreadUtil.h"
      69             : #include "ps/TouchInput.h"
      70             : #include "ps/UserReport.h"
      71             : #include "ps/VideoMode.h"
      72             : #include "ps/World.h"
      73             : #include "ps/XMB/XMBData.h"
      74             : #include "ps/XMB/XMBStorage.h"
      75             : #include "ps/XML/Xeromyces.h"
      76             : #include "ps/scripting/JSInterface_Game.h"
      77             : #include "ps/scripting/JSInterface_Main.h"
      78             : #include "ps/scripting/JSInterface_VFS.h"
      79             : #include "renderer/Renderer.h"
      80             : #include "renderer/RenderingOptions.h"
      81             : #include "renderer/SceneRenderer.h"
      82             : #include "scriptinterface/FunctionWrapper.h"
      83             : #include "scriptinterface/Object.h"
      84             : #include "scriptinterface/Context.h"
      85             : #include "scriptinterface/Conversions.h"
      86             : #include "scriptinterface/Interface.h"
      87             : #include "scriptinterface/Request.h"
      88             : #include "scriptinterface/Stats.h"
      89             : #include "simulation2/Simulation2.h"
      90             : #include "simulation2/scripting/JSInterface_Simulation.h"
      91             : #include "simulation2/system/Component.h"
      92             : #include "soundmanager/ISoundManager.h"
      93             : 
      94             : #include <SDL.h>
      95             : #include <SDL_error.h>
      96             : #include <SDL_hints.h>
      97             : #include <SDL_keyboard.h>
      98             : #include <SDL_version.h>
      99             : #include <algorithm>
     100             : #include <boost/algorithm/string/classification.hpp>
     101             : #include <boost/algorithm/string/constants.hpp>
     102             : #include <boost/algorithm/string/join.hpp>
     103             : #include <boost/algorithm/string/split.hpp>
     104             : #include <chrono>
     105             : #include <cstdlib>
     106             : #include <ctime>
     107             : #include <filesystem>
     108             : #include <fmt/format.h>
     109             : #include <fstream>
     110             : #include <js/CallArgs.h>
     111             : #include <js/Promise.h>
     112             : #include <js/RootingAPI.h>
     113             : #include <js/TypeDecls.h>
     114             : #include <js/Value.h>
     115             : #include <locale>
     116             : #include <memory>
     117             : #include <optional>
     118             : #include <stdexcept>
     119             : #include <string>
     120             : #include <thread>
     121             : #include <unordered_set>
     122             : #include <utility>
     123             : 
     124             : extern void RestartEngine();
     125             : 
     126             : using namespace std::literals;
     127             : 
     128             : ERROR_GROUP(System);
     129             : ERROR_TYPE(System, SDLInitFailed);
     130             : ERROR_TYPE(System, VmodeFailed);
     131             : ERROR_TYPE(System, RequiredExtensionsMissing);
     132             : 
     133           0 : thread_local std::shared_ptr<Script::Context> g_ScriptContext;
     134             : 
     135             : bool g_InDevelopmentCopy;
     136             : bool g_CheckedIfInDevelopmentCopy = false;
     137             : 
     138           0 : ErrorReactionInternal psDisplayError(const wchar_t* /*text*/, size_t /*flags*/)
     139             : {
     140             :     // If we're fullscreen, then sometimes (at least on some particular drivers on Linux)
     141             :     // displaying the error dialog hangs the desktop since the dialog box is behind the
     142             :     // fullscreen window. So we just force the game to windowed mode before displaying the dialog.
     143             :     // (But only if we're in the main thread, and not if we're being reentrant.)
     144           0 :     if (Threading::IsMainThread())
     145             :     {
     146           0 :         static bool reentering = false;
     147           0 :         if (!reentering)
     148             :         {
     149           0 :             reentering = true;
     150           0 :             g_VideoMode.SetFullscreen(false);
     151           0 :             reentering = false;
     152             :         }
     153             :     }
     154             : 
     155             :     // We don't actually implement the error display here, so return appropriately
     156           0 :     return ERI_NOT_IMPLEMENTED;
     157             : }
     158             : 
     159           0 : void MountMods(const Paths& paths, const std::vector<CStr>& mods)
     160             : {
     161           0 :     OsPath modPath = paths.RData()/"mods";
     162           0 :     OsPath modUserPath = paths.UserData()/"mods";
     163             : 
     164           0 :     size_t userFlags = VFS_MOUNT_WATCH|VFS_MOUNT_ARCHIVABLE;
     165           0 :     size_t baseFlags = userFlags|VFS_MOUNT_MUST_EXIST;
     166           0 :     size_t priority = 0;
     167           0 :     for (size_t i = 0; i < mods.size(); ++i)
     168             :     {
     169           0 :         priority = i + 1; // Mods are higher priority than regular mountings, which default to priority 0
     170             : 
     171           0 :         OsPath modName(mods[i]);
     172             :         // Only mount mods from the user path if they don't exist in the 'rdata' path.
     173           0 :         if (DirectoryExists(modPath / modName / ""))
     174           0 :             g_VFS->Mount(L"", modPath / modName / "", baseFlags, priority);
     175             :         else
     176           0 :             g_VFS->Mount(L"", modUserPath / modName / "", userFlags, priority);
     177             : 
     178             :         // If mod have a config/<modName>.cfg, load the configuration.
     179           0 :         VfsPath modConfigPath{fmt::format("config/{}.cfg", mods[i].c_str())};
     180           0 :         if (!VfsFileExists(modConfigPath))
     181           0 :             continue;
     182             : 
     183           0 :         g_ConfigDB.SetConfigFile(CFG_MOD, modConfigPath);
     184           0 :         g_ConfigDB.Reload(CFG_MOD);
     185           0 :     }
     186             : 
     187             :     // Mount the user mod last. In dev copy, mount it with a low priority. Otherwise, make it writable.
     188           0 :     g_VFS->Mount(L"", modUserPath / "user" / "", userFlags, InDevelopmentCopy() ? 0 : priority + 1);
     189           0 : }
     190             : 
     191           0 : void InitVfs(const CmdLineArgs& args)
     192             : {
     193           0 :     PROFILE2("InitVfs");
     194             : 
     195           0 :     const Paths paths(args);
     196             : 
     197           0 :     OsPath logs(paths.Logs());
     198           0 :     CreateDirectories(logs, 0700);
     199             : 
     200           0 :     psSetLogDir(logs);
     201             :     // desired location for crashlog is now known. update AppHooks ASAP
     202             :     // (particularly before the following error-prone operations):
     203           0 :     app_hooks_update({
     204             :         .get_log_dir = psLogDir,
     205             :         .bundle_logs = psBundleLogs,
     206             :         .display_error = psDisplayError
     207             :     });
     208             : 
     209           0 :     g_VFS = CreateVfs();
     210             : 
     211           0 :     const OsPath readonlyConfig = paths.RData()/"config"/"";
     212             : 
     213             :     // Mount these dirs with highest priority so that mods can't overwrite them.
     214           0 :     g_VFS->Mount(L"cache/", paths.Cache(), VFS_MOUNT_ARCHIVABLE, VFS_MAX_PRIORITY);    // (adding XMBs to archive speeds up subsequent reads)
     215           0 :     if (readonlyConfig != paths.Config())
     216           0 :         g_VFS->Mount(L"config/", readonlyConfig, 0, VFS_MAX_PRIORITY-1);
     217           0 :     g_VFS->Mount(L"config/", paths.Config(), 0, VFS_MAX_PRIORITY);
     218           0 :     g_VFS->Mount(L"screenshots/", paths.UserData()/"screenshots"/"", 0, VFS_MAX_PRIORITY);
     219           0 :     g_VFS->Mount(L"saves/", paths.UserData()/"saves"/"", VFS_MOUNT_WATCH, VFS_MAX_PRIORITY);
     220             : 
     221             :     // Engine localization files (regular priority, these can be overwritten).
     222           0 :     g_VFS->Mount(L"l10n/", paths.RData()/"l10n"/"");
     223             : 
     224             :     // Mods will be mounted later.
     225             : 
     226             :     // note: don't bother with g_VFS->TextRepresentation - directories
     227             :     // haven't yet been populated and are empty.
     228           0 : }
     229             : 
     230             : 
     231           0 : static void InitPs(bool setup_gui, const CStrW& gui_page, Script::Interface* srcScriptInterface, JS::HandleValue initData)
     232             : {
     233           0 :     g_Console->Init();
     234           0 :     LoadHotkeys(g_ConfigDB);
     235             : 
     236           0 :     if (!setup_gui)
     237             :     {
     238             :         // We do actually need *some* kind of GUI loaded, so use the
     239             :         // (currently empty) Atlas one
     240           0 :         g_GUI->SwitchPage(L"page_atlas.xml", srcScriptInterface, initData);
     241           0 :         return;
     242             :     }
     243             : 
     244             :     // GUI uses VFS, so this must come after VFS init.
     245           0 :     g_GUI->SwitchPage(gui_page, srcScriptInterface, initData);
     246             : }
     247             : 
     248           1 : [[nodiscard]] std::unique_ptr<InputHandlers> MakeInputHandlers()
     249             : {
     250           1 :     g_Joystick.Initialise();
     251             : 
     252           1 :     std::unique_ptr<InputHandlers> handlers{std::make_unique<InputHandlers>()};
     253             : 
     254           1 :     handlers->emplace(g_VideoMode.m_InputManager, Input::Slot::HOTKEY_INPUT, HotkeyInputActualHandler);
     255             : 
     256           1 :     handlers->emplace(g_VideoMode.m_InputManager, Input::Slot::TOUCH_INPUT, touch_input_handler);
     257             : 
     258             :     // Should be called after scancode map update (i.e. after the global input, but before UI).
     259             :     // This never blocks the event, but it does some processing necessary for hotkeys,
     260             :     // which are triggered later down the input chain.
     261             :     // (by calling this before the UI, we can use 'EventWouldTriggerHotkey' in the UI).
     262           1 :     handlers->emplace(g_VideoMode.m_InputManager, Input::Slot::HOTKEY_INPUT_PREPARATION,
     263             :         HotkeyInputPrepHandler);
     264             : 
     265             :     // These two must be called first (i.e. pushed last)
     266             :     // GlobalsInputHandler deals with some important global state,
     267             :     // such as which scancodes are being pressed, mouse buttons pressed, etc.
     268             :     // while HotkeyStateChange updates the map of active hotkeys.
     269           1 :     handlers->emplace(g_VideoMode.m_InputManager, Input::Slot::GLOBAL, GlobalsInputHandler);
     270           1 :     handlers->emplace(g_VideoMode.m_InputManager, Input::Slot::HOTKEY_STATE_CHANGE, HotkeyStateChange);
     271             : 
     272           1 :     return handlers;
     273           0 : }
     274             : 
     275             : 
     276           0 : static void ShutdownPs()
     277             : {
     278           0 :     SAFE_DELETE(g_GUI);
     279             : 
     280           0 :     UnloadHotkeys();
     281           0 : }
     282             : 
     283           0 : static void InitSDL()
     284             : {
     285           0 :     if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_NOPARACHUTE) < 0)
     286             :     {
     287           0 :         LOGERROR("SDL library initialization failed: {}", SDL_GetError());
     288           0 :         throw PSERROR_System_SDLInitFailed();
     289             :     }
     290           0 :     atexit(SDL_Quit);
     291             : 
     292             :     // Text input is active by default, disable it until it is actually needed.
     293           0 :     SDL_StopTextInput();
     294             : 
     295             : #if SDL_VERSION_ATLEAST(2, 0, 9)
     296             :     // SDL2 >= 2.0.9 defaults to 32 pixels (to support touch screens) but that can break our double-clicking.
     297           0 :     SDL_SetHint(SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS, "1");
     298             : #endif
     299             : 
     300             : #if OS_MACOSX
     301             :     // Some Mac mice only have one button, so they can't right-click
     302             :     // but SDL2 can emulate that with Ctrl+Click
     303             :     SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK,
     304             :         g_ConfigDB.Get("macmouse", false) ? "1" : "0");
     305             : #endif
     306           0 : }
     307             : 
     308           0 : static void ShutdownSDL()
     309             : {
     310           0 :     PROFILE2("ShutdownSDL");
     311           0 :     SDL_Quit();
     312           0 : }
     313             : 
     314             : 
     315           0 : void EndGame()
     316             : {
     317           0 :     SAFE_DELETE(g_NetClient);
     318           0 :     SAFE_DELETE(g_NetServer);
     319           0 :     SAFE_DELETE(g_Game);
     320             : 
     321           0 :     if (CRenderer::IsInitialised())
     322             :     {
     323           0 :         ISoundManager::CloseGame();
     324           0 :         g_Renderer.GetSceneRenderer().ResetState();
     325             :     }
     326           0 : }
     327             : 
     328           0 : void ShutdownNetworkAndUI()
     329             : {
     330           0 :     const bool hasRenderer = CRenderer::IsInitialised();
     331             : 
     332           0 :     EndGame();
     333             : 
     334             : #if CONFIG2_LOBBY
     335           0 :     SAFE_DELETE(g_XmppClient);
     336             : #endif
     337             : 
     338           0 :     SAFE_DELETE(g_ModIo);
     339             : 
     340           0 :     ShutdownPs();
     341             : 
     342           0 :     if (hasRenderer)
     343           0 :         delete &g_Renderer;
     344             : 
     345           0 :     g_RenderingOptions.ClearHooks();
     346             : 
     347           0 :     g_Profiler2.ShutDownHTTP();
     348           0 :     g_Profiler2.ShutdownGPU();
     349             : 
     350           0 :     if (hasRenderer)
     351           0 :         g_VideoMode.Shutdown();
     352             : 
     353           0 :     ShutdownSDL();
     354           0 :     g_UserReporter.Deinitialize();
     355             : 
     356             :     // Cleanup curl now that g_ModIo and g_UserReporter have been shutdown.
     357           0 :     curl_global_cleanup();
     358             : 
     359           0 :     delete &g_L10n;
     360           0 : }
     361             : 
     362           0 : void ShutdownConfigAndSubsequent()
     363             : {
     364           0 :     CConfigDB::Shutdown();
     365             : 
     366           0 :     SAFE_DELETE(g_Console);
     367             : 
     368             :     // This is needed to ensure that no callbacks from the JSAPI try to use
     369             :     // the profiler when it's already destructed
     370           0 :     g_ScriptContext.reset();
     371             : 
     372             :     // resource
     373             :     // first shut down all resource owners, and then the handle manager.
     374           0 :     {
     375           0 :         PROFILE2("resource modules");
     376             : 
     377           0 :         ISoundManager::SetEnabled(false);
     378             : 
     379           0 :         g_VFS.reset();
     380             : 
     381           0 :         file_stats_dump();
     382           0 :     }
     383             : 
     384           0 :     PROFILE2("shutdown misc");
     385             : 
     386           0 :     CNetHost::Deinitialize();
     387             : 
     388             :     // Should be destroyed last, since the above uses them.
     389           0 :     delete &g_Profiler;
     390           0 :     delete &g_ProfileViewer;
     391             : 
     392           0 :     SAFE_DELETE(g_ScriptStatsTable);
     393           0 : }
     394             : 
     395             : #if OS_UNIX
     396           0 : static void FixLocales()
     397             : {
     398             : #if OS_MACOSX || OS_BSD
     399             :     // OS X requires a UTF-8 locale in LC_CTYPE so that *wprintf can handle
     400             :     // wide characters. Peculiarly the string "UTF-8" seems to be acceptable
     401             :     // despite not being a real locale, and it's conveniently language-agnostic,
     402             :     // so use that.
     403             :     setlocale(LC_CTYPE, "UTF-8");
     404             : #endif
     405             : 
     406             : 
     407             :     // On misconfigured systems with incorrect locale settings, we'll die
     408             :     // with a C++ exception when some code (e.g. Boost) tries to use locales.
     409             :     // To avoid death, we'll detect the problem here and warn the user and
     410             :     // reset to the default C locale.
     411             : 
     412             : 
     413             :     // For informing the user of the problem, use the list of env vars that
     414             :     // glibc setlocale looks at. (LC_ALL is checked first, and LANG last.)
     415           0 :     const char* const LocaleEnvVars[] = {
     416             :         "LC_ALL",
     417             :         "LC_COLLATE",
     418             :         "LC_CTYPE",
     419             :         "LC_MONETARY",
     420             :         "LC_NUMERIC",
     421             :         "LC_TIME",
     422             :         "LC_MESSAGES",
     423             :         "LANG"
     424             :     };
     425             : 
     426           0 :     try
     427             :     {
     428             :         // this constructor is similar to setlocale(LC_ALL, ""),
     429             :         // but instead of returning NULL, it throws runtime_error
     430             :         // when the first locale env variable found contains an invalid value
     431           0 :         std::locale("");
     432             :     }
     433           0 :     catch (std::runtime_error&)
     434             :     {
     435           0 :         LOGWARNING("Invalid locale settings");
     436             : 
     437           0 :         for (size_t i = 0; i < ARRAY_SIZE(LocaleEnvVars); i++)
     438             :         {
     439           0 :             if (char* envval = getenv(LocaleEnvVars[i]))
     440           0 :                 LOGWARNING("  {}=\"{}\"", LocaleEnvVars[i], envval);
     441             :             else
     442           0 :                 LOGWARNING("  {}=\"(unset)\"", LocaleEnvVars[i]);
     443             :         }
     444             : 
     445             :         // We should set LC_ALL since it overrides LANG
     446           0 :         if (setenv("LC_ALL", std::locale::classic().name().c_str(), 1))
     447           0 :             debug_warn(L"Invalid locale settings, and unable to set LC_ALL env variable.");
     448             :         else
     449           0 :             LOGWARNING("Setting LC_ALL env variable to: {}", getenv("LC_ALL"));
     450           0 :     }
     451           0 : }
     452             : #else
     453             : static void FixLocales()
     454             : {
     455             :     // Do nothing on Windows
     456             : }
     457             : #endif
     458             : 
     459           0 : void EarlyInit()
     460             : {
     461             :     // If you ever want to catch a particular allocation:
     462             :     //_CrtSetBreakAlloc(232647);
     463             : 
     464           0 :     Threading::SetMainThread();
     465             : 
     466           0 :     debug_SetThreadName("main");
     467             : 
     468           0 :     timer_Init();
     469             : 
     470             :     // initialise profiler early so it can profile startup,
     471             :     // but only after LatchStartTime
     472           0 :     g_Profiler2.Initialise();
     473             : 
     474           0 :     FixLocales();
     475             : 
     476             :     // Initialise the low-quality rand function
     477           0 :     srand(time(NULL));  // NOTE: this rand should *not* be used for simulation!
     478           0 : }
     479             : 
     480             : bool Autostart(const CmdLineArgs& args);
     481             : 
     482             : /**
     483             :  * Returns true if the user has intended to start a visual replay from command line.
     484             :  */
     485             : bool AutostartVisualReplay(const std::string& replayFile);
     486             : 
     487           0 : bool Init(const CmdLineArgs& args, int flags)
     488             : {
     489           0 :     new CProfileViewer;
     490           0 :     new CProfileManager;    // before any script code
     491             : 
     492           0 :     g_ScriptStatsTable = new Script::CScriptStatsTable;
     493           0 :     g_ProfileViewer.AddRootTable(g_ScriptStatsTable);
     494             : 
     495             :     // Set up the console early, so that debugging
     496             :     // messages can be logged to it. (The console's size
     497             :     // and fonts are set later in InitPs())
     498           0 :     g_Console = new CConsole();
     499             : 
     500             :     // g_ConfigDB, command line args, globals
     501           0 :     CONFIG_Init(args);
     502             : 
     503             :     // Using a global object for the context is a workaround until Simulation and AI use
     504             :     // their own threads and also their own contexts.
     505           0 :     const int contextSize = 384 * 1024 * 1024;
     506           0 :     const int heapGrowthBytesGCTrigger = 12 * 1024 * 1024;
     507           0 :     g_ScriptContext = std::make_shared<Script::Context>(contextSize, heapGrowthBytesGCTrigger);
     508             : 
     509             :     // On the first Init (INIT_MODS), check for command-line arguments
     510             :     // or use the default mods from the config and enable those.
     511             :     // On later engine restarts (e.g. the mod selector), we will skip this path,
     512             :     // to avoid overwriting the newly selected mods.
     513           0 :     if (flags & INIT_MODS)
     514             :     {
     515           0 :         Script::Interface modInterface("Engine", "Mod", g_ScriptContext);
     516           0 :         g_Mods.UpdateAvailableMods(modInterface);
     517           0 :         std::vector<CStr> mods;
     518           0 :         if (args.Has("mod"))
     519           0 :             mods = args.GetMultiple("mod");
     520             :         else
     521             :         {
     522           0 :             boost::split(mods, g_ConfigDB.Get("mod.enabledmods", std::string{}),
     523           0 :                 boost::algorithm::is_space(), boost::token_compress_on);
     524             :         }
     525             : 
     526           0 :         if (!g_Mods.EnableMods(mods, flags & INIT_MODS_PUBLIC))
     527             :         {
     528             :             // In non-visual mode, fail entirely.
     529           0 :             if (args.Has("autostart-nonvisual"))
     530             :             {
     531           0 :                 LOGERROR("Trying to start with incompatible mods: {}.",
     532             :                     boost::algorithm::join(g_Mods.GetIncompatibleMods(), ", "));
     533           0 :                 return false;
     534             :             }
     535             :         }
     536           0 :     }
     537             :     // If there are incompatible mods, switch to the mod selector if available
     538             :     // so players can resolve the problem, otherwise just complain and load
     539             :     // default mods.
     540           0 :     if (g_Mods.GetIncompatibleMods().empty())
     541           0 :         MountMods(Paths(args), g_Mods.GetEnabledMods());
     542           0 :     else if (flags & INIT_NO_GUI)
     543             :     {
     544           0 :         LOGERROR("Trying to start with incompatible mods: {}.",
     545             :             boost::algorithm::join(g_Mods.GetIncompatibleMods(), ", "));
     546           0 :         MountMods(Paths(args), { "mod", "public" });
     547             :     }
     548             :     else
     549           0 :         MountMods(Paths(args), { "mod" });
     550             : 
     551             :     // Special command-line mode to dump the entity schemas instead of running the game.
     552             :     // (This must be done after loading VFS etc, but should be done before wasting time
     553             :     // on anything else.)
     554           0 :     if (args.Has("dumpSchema"))
     555             :     {
     556           0 :         try
     557             :         {
     558           0 :             CSimulation2 sim{NULL, *g_ScriptContext, NULL, CSimulation2::DEFAULT_SCRIPTS};
     559           0 :             std::ofstream f("entity.rng", std::ios_base::out | std::ios_base::trunc);
     560           0 :             f << sim.GenerateSchema();
     561           0 :             debug_printf("Generated entity.rng\n");
     562           0 :         }
     563           0 :         catch (const CSimulation2::LoadScriptError& e)
     564             :         {
     565           0 :             LOGERROR("{}", e.what());
     566           0 :         }
     567           0 :         return false;
     568             :     }
     569             : 
     570           0 :     CNetHost::Initialize();
     571             : 
     572             : #if CONFIG2_AUDIO
     573           0 :     if (!args.Has("autostart-nonvisual") && !g_DisableAudio)
     574           0 :         ISoundManager::CreateSoundManager();
     575             : #endif
     576             : 
     577           0 :     new L10n;
     578             : 
     579             :     // Optionally start profiler HTTP output automatically
     580             :     // (By default it's only enabled by a hotkey, for security/performance)
     581           0 :     if (g_ConfigDB.Get("profiler2.autoenable", false))
     582           0 :         g_Profiler2.EnableHTTP();
     583             : 
     584             :     // Initialise everything except Win32 sockets (because our networking
     585             :     // system already inits those)
     586           0 :     curl_global_init(CURL_GLOBAL_ALL & ~CURL_GLOBAL_WIN32);
     587             : 
     588           0 :     if (!g_Quickstart)
     589           0 :         g_UserReporter.Initialize(); // after config
     590             : 
     591           0 :     PROFILE2_EVENT("Init finished");
     592             :     return true;
     593           0 : }
     594             : 
     595           0 : [[nodiscard]] std::unique_ptr<InputHandlers> InitGraphics(const CmdLineArgs& args, int flags,
     596             :     const std::vector<CStr>& installedMods, Script::Context& scriptContext,
     597             :     Script::Interface& scriptInterface)
     598             : {
     599           0 :     const bool setup_vmode = (flags & INIT_HAVE_VMODE) == 0;
     600             : 
     601           0 :     if(setup_vmode)
     602             :     {
     603           0 :         InitSDL();
     604             : 
     605           0 :         if (!g_VideoMode.InitSDL())
     606           0 :             throw PSERROR_System_VmodeFailed(); // abort startup
     607             :     }
     608             : 
     609           0 :     RunHardwareDetection(!g_Quickstart, g_VideoMode.GetBackendDevice());
     610             : 
     611             :     // Optionally start profiler GPU timings automatically
     612             :     // (By default it's only enabled by a hotkey, for performance/compatibility)
     613           0 :     if (g_ConfigDB.Get("profiler2.autoenable", false))
     614           0 :         g_Profiler2.EnableGPU();
     615             : 
     616           0 :     if(g_DisableAudio)
     617           0 :         ISoundManager::SetEnabled(false);
     618             : 
     619           0 :     g_GUI = new CGUIManager{scriptContext, scriptInterface};
     620             : 
     621           0 :     g_RenderingOptions.ReadConfigAndSetupHooks();
     622             : 
     623             :     // create renderer
     624           0 :     new CRenderer(g_VideoMode.GetBackendDevice());
     625             : 
     626           0 :     std::unique_ptr<InputHandlers> handlers{MakeInputHandlers()};
     627             : 
     628             :     // TODO: Is this the best place for this?
     629           0 :     if (VfsDirectoryExists(L"maps/"))
     630           0 :         g_Xeromyces.AddValidator(g_VFS, "map", "maps/scenario.rng");
     631             : 
     632           0 :     try
     633             :     {
     634           0 :         if (!AutostartVisualReplay(args.Get("replay-visual")) && !Autostart(args))
     635             :         {
     636           0 :             const bool setup_gui = ((flags & INIT_NO_GUI) == 0);
     637             : 
     638           0 :             Script::Request rq{g_GUI->GetScriptInterface()};
     639           0 :             JS::RootedValue data(rq.cx);
     640           0 :             Script::CreateObject(rq, &data, "isStartup", true);
     641           0 :             if (!installedMods.empty())
     642           0 :                 Script::SetProperty(rq, data, "installedMods", installedMods);
     643           0 :             InitPs(setup_gui, installedMods.empty() ? L"page_pregame.xml" : L"page_modmod.xml", &g_GUI->GetScriptInterface(), data);
     644           0 :         }
     645             :     }
     646           0 :     catch (PSERROR_Game_World_MapLoadFailed& e)
     647             :     {
     648             :         // Map Loading failed
     649             : 
     650             :         // Start the engine so we have a GUI
     651           0 :         InitPs(true, L"page_pregame.xml", NULL, JS::UndefinedHandleValue);
     652             : 
     653             :         // Call script function to do the actual work
     654             :         //  (delete game data, switch GUI page, show error, etc.)
     655           0 :         CancelLoad(CStr(e.what()).FromUTF8());
     656           0 :     }
     657             : 
     658           0 :     return handlers;
     659           0 : }
     660             : 
     661           0 : bool InitNonVisual(const CmdLineArgs& args)
     662             : {
     663           0 :     return Autostart(args);
     664             : }
     665             : 
     666             : /**
     667             :  * Temporarily loads a scenario map and retrieves the "ScriptSettings" JSON
     668             :  * data from it.
     669             :  * The scenario map format is used for scenario and skirmish map types (random
     670             :  * games do not use a "map" (format) but a small JavaScript program which
     671             :  * creates a map on the fly). It contains a section to initialize the game
     672             :  * setup screen.
     673             :  * @param mapPath Absolute path (from VFS root) to the map file to peek in.
     674             :  * @return ScriptSettings in JSON format extracted from the map.
     675             :  */
     676           0 : CStr8 LoadSettingsOfScenarioMap(const VfsPath &mapPath)
     677             : {
     678           0 :     CXeromyces mapFile;
     679           0 :     const char *pathToSettings[] =
     680             :     {
     681             :         "Scenario", "ScriptSettings", ""  // Path to JSON data in map
     682             :     };
     683             : 
     684           0 :     Status loadResult = mapFile.Load(g_VFS, mapPath);
     685             : 
     686           0 :     if (INFO::OK != loadResult)
     687             :     {
     688           0 :         LOGERROR("LoadSettingsOfScenarioMap: Unable to load map file '{}'", mapPath.string8());
     689           0 :         throw PSERROR_Game_World_MapLoadFailed("Unable to load map file, check the path for typos.");
     690             :     }
     691           0 :     XMBElement mapElement = mapFile.GetRoot();
     692             : 
     693             :     // Select the ScriptSettings node in the map file...
     694           0 :     for (int i = 0; pathToSettings[i][0]; ++i)
     695             :     {
     696           0 :         int childId = mapFile.GetElementID(pathToSettings[i]);
     697             : 
     698           0 :         XMBElementList nodes = mapElement.GetChildNodes();
     699           0 :         auto it = std::find_if(nodes.begin(), nodes.end(), [&childId](const XMBElement& child) {
     700           0 :             return child.GetNodeName() == childId;
     701             :         });
     702             : 
     703           0 :         if (it != nodes.end())
     704           0 :             mapElement = *it;
     705             :     }
     706             :     // ... they contain a JSON document to initialize the game setup
     707             :     // screen
     708           0 :     return mapElement.GetText();
     709           0 : }
     710             : 
     711             : /**
     712             :  * Autostart arguments are parsed in javascript for convenience and moddability.
     713             :  * This C++ part only handles the following arguments:
     714             :  * -autostart=MAP       to enable regular autostart / host mode autostart
     715             :  * -autostart-client=IP to enable 'MP client' autostart.
     716             :  * -autostart-host      to enable 'MP host' autostart.
     717             :  * -autostart-nonvisual to start in non-visual mode.
     718             :  *  TODO: it might be nice to move these to JS too.
     719             :  */
     720           0 : bool Autostart(const CmdLineArgs& args)
     721             : {
     722           0 :     if (!args.Has("autostart-client") && !args.Has("autostart"))
     723             :         return false;
     724             : 
     725             :     // Create some scriptinterface to store the js values for the settings.
     726           0 :     Script::Interface scriptInterface("Engine", "Game Setup", g_ScriptContext);
     727           0 :     Script::Request rq(scriptInterface);
     728             : 
     729             :     // We use the javascript gameSettings to handle options, but that requires running JS.
     730             :     // Since we don't want to use the full Gui manager, we load an entrypoint script
     731             :     // that can run the priviledged "LoadScript" function, and then call the appropriate function.
     732             : 
     733             :     // TODO: this essentially duplicates the CGUI logic to load directory or scripts.
     734           0 :     std::unordered_set<VfsPath> templateCache;
     735           0 :     const auto autostartLoadScript = [&templateCache](const Script::Interface& scriptInterface,
     736           0 :         const VfsPath& path)
     737             :     {
     738           0 :         if (!std::get<1>(templateCache.insert(path)))
     739             :             return;
     740             : 
     741           0 :         if (path.IsDirectory())
     742             :         {
     743           0 :             VfsPaths pathnames;
     744           0 :             vfs::GetPathnames(g_VFS, path, L"*.js", pathnames);
     745           0 :             for (const VfsPath& file : pathnames)
     746           0 :                 scriptInterface.LoadGlobalScriptFile(file);
     747           0 :         }
     748             :         else
     749           0 :             scriptInterface.LoadGlobalScriptFile(path);
     750           0 :     };
     751             : 
     752           0 :     const auto loadScriptCallback = Script::Function::Register(rq, "LoadScript", autostartLoadScript);
     753             :     // Load the entire folder to allow mods to extend the entrypoint without copying the whole file.
     754           0 :     autostartLoadScript(scriptInterface, VfsPath(L"autostart/"));
     755             : 
     756             :     // Provide some required functions to the script.
     757             : 
     758           0 :     struct GetTemplate
     759             :     {
     760             :         CTemplateLoader templateLoader;
     761             : 
     762           0 :         CParamNode operator()(const std::string& templateName){
     763             :             // TODO: this essentially duplicates the CGUI function
     764           0 :             const CParamNode& templateRoot{
     765           0 :                 templateLoader.GetTemplateFileData(templateName).GetOnlyChild()};
     766           0 :             if (!templateRoot.IsOk())
     767           0 :                 LOGERROR("Invalid template found for '{}'", templateName);
     768             : 
     769           0 :             return templateRoot;
     770             :         }
     771             :     };
     772             : 
     773           0 :     std::optional<Script::Function::StatefulCallback<GetTemplate>> getTemplateCallback;
     774           0 :     if (args.Has("autostart-nonvisual"))
     775           0 :         getTemplateCallback.emplace(rq, "GetTemplate", GetTemplate{});
     776             :     else
     777             :     {
     778           0 :         JSI_GUIManager::RegisterScriptFunctions(rq);
     779             :         // TODO: this loads pregame, which is hardcoded to exist by various code paths. That ought be changed.
     780           0 :         InitPs(false, L"page_pregame.xml", &g_GUI->GetScriptInterface(), JS::UndefinedHandleValue);
     781             :     }
     782             : 
     783           0 :     JSI_Game::RegisterScriptFunctions(rq);
     784           0 :     JSI_Main::RegisterScriptFunctions(rq);
     785           0 :     JSI_Simulation::RegisterScriptFunctions(rq);
     786           0 :     JSI_VFS::RegisterScriptFunctions_ReadWriteAnywhere(rq);
     787           0 :     JSI_Network::RegisterScriptFunctions(rq);
     788             : 
     789           0 :     JS::RootedValue cmdLineArgs(rq.cx);
     790           0 :     Script::ToJSVal(rq, &cmdLineArgs, args);
     791             : 
     792             :     // Pass the default port if undefined, to avoid duplicating it in JS.
     793           0 :     if (!Script::HasProperty(rq, cmdLineArgs, "autostart-port"))
     794           0 :         Script::SetProperty(rq, cmdLineArgs, "autostart-port", PS_DEFAULT_PORT);
     795             : 
     796           0 :     JS::RootedValue resultValue{rq.cx};
     797           0 :     JS::RootedValue global(rq.cx, rq.globalValue());
     798           0 :     if (!Script::Function::Call(rq, global,
     799           0 :         args.Has("autostart-client") ? "autostartClient" : "autostartHost", &resultValue,
     800           0 :         cmdLineArgs, args.Has("autostart-host")) && !resultValue.isObject())
     801             :     {
     802             :         return false;
     803             :     }
     804             : 
     805           0 :     JS::RootedObject result{rq.cx, &resultValue.toObject()};
     806           0 :     while (JS::IsPromiseObject(result) && JS::GetPromiseState(result) == JS::PromiseState::Pending)
     807             :     {
     808           0 :         g_ScriptContext->RunJobs();
     809           0 :         g_NetClient->Poll();
     810           0 :         std::this_thread::sleep_for(std::chrono::microseconds(200));
     811             :     }
     812           0 :     if (JS::IsPromiseObject(result) && JS::GetPromiseState(result) == JS::PromiseState::Rejected)
     813           0 :         return false;
     814             : 
     815           0 :     JS::RootedValue pageData{rq.cx, JS::IsPromiseObject(result) ? JS::GetPromiseResult(result) :
     816           0 :         resultValue};
     817             : 
     818           0 :     if (args.Has("autostart-nonvisual"))
     819             :     {
     820           0 :         PS::Loader::NonprogressiveLoad();
     821           0 :         g_Game->ReallyStartGame();
     822             :         return true;
     823             :     }
     824             : 
     825           0 :     std::wstring pageName;
     826           0 :     Script::GetPropertyInt(rq, pageData, 0, pageName);
     827           0 :     JS::RootedValue pageArgs{rq.cx};
     828           0 :     Script::GetPropertyInt(rq, pageData, 1, &pageArgs);
     829           0 :     Script::StructuredClone clonedpageArgs{Script::WriteStructuredClone(rq, pageArgs)};
     830             : 
     831           0 :     g_GUI->SwitchPage(pageName, &scriptInterface, pageArgs);
     832             : 
     833           0 :     return true;
     834           0 : }
     835             : 
     836           0 : bool AutostartVisualReplay(const std::string& replayFile)
     837             : {
     838           0 :     if (!std::filesystem::is_regular_file(replayFile))
     839             :         return false;
     840             : 
     841           0 :     g_Game = new CGame(false);
     842           0 :     g_Game->SetPlayerID(-1);
     843           0 :     g_Game->StartVisualReplay(replayFile);
     844             : 
     845           0 :     Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface();
     846           0 :     Script::Request rq(scriptInterface);
     847           0 :     JS::RootedValue attrs(rq.cx, g_Game->GetSimulation2()->GetInitAttributes());
     848             : 
     849           0 :     JS::RootedValue playerAssignments(rq.cx);
     850           0 :     Script::CreateObject(rq, &playerAssignments);
     851           0 :     JS::RootedValue localPlayer(rq.cx);
     852           0 :     Script::CreateObject(rq, &localPlayer, "player", g_Game->GetPlayerID());
     853           0 :     Script::SetProperty(rq, playerAssignments, "local", localPlayer);
     854             : 
     855           0 :     JS::RootedValue sessionInitData(rq.cx);
     856             : 
     857           0 :     Script::CreateObject(
     858             :         rq,
     859             :         &sessionInitData,
     860             :         "attribs", attrs,
     861             :         "playerAssignments", playerAssignments);
     862             : 
     863           0 :     InitPs(true, L"page_loading.xml", &scriptInterface, sessionInitData);
     864             : 
     865           0 :     return true;
     866           0 : }
     867             : 
     868           0 : void CancelLoad(const CStrW& message)
     869             : {
     870           0 :     std::shared_ptr<Script::Interface> pScriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface();
     871           0 :     Script::Request rq(pScriptInterface);
     872             : 
     873           0 :     JS::RootedValue global(rq.cx, rq.globalValue());
     874             : 
     875           0 :     PS::Loader::Cancel();
     876             : 
     877           0 :     if (g_GUI &&
     878           0 :         g_GUI->GetPageCount() &&
     879           0 :         Script::HasProperty(rq, global, "cancelOnLoadGameError"))
     880           0 :         Script::Function::CallVoid(rq, global, "cancelOnLoadGameError", message);
     881           0 : }
     882             : 
     883           0 : bool InDevelopmentCopy()
     884             : {
     885           0 :     if (!g_CheckedIfInDevelopmentCopy)
     886             :     {
     887           0 :         g_InDevelopmentCopy = (g_VFS->GetFileInfo(L"config/dev.cfg", NULL) == INFO::OK);
     888           0 :         g_CheckedIfInDevelopmentCopy = true;
     889             :     }
     890           0 :     return g_InDevelopmentCopy;
     891             : }

Generated by: LCOV version 1.16