Files
OpenRCT2-Web/src/openrct2/Context.cpp
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1750 lines
57 KiB
C++
Raw Normal View History

/*****************************************************************************
2026-01-05 14:42:59 +01:00
* Copyright (c) 2014-2026 OpenRCT2 developers
2018-06-15 14:07:34 +02:00
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
2017-09-04 23:17:35 +02:00
#ifdef __EMSCRIPTEN__
#include <cassert>
#include <emscripten.h>
2017-09-04 23:17:35 +02:00
#endif // __EMSCRIPTEN__
2018-11-21 23:16:04 +01:00
2022-09-18 16:15:42 +01:00
#include "AssetPackManager.h"
#include "Context.h"
2018-06-22 23:25:16 +02:00
#include "FileClassifier.h"
#include "Game.h"
#include "GameState.h"
2019-05-11 21:31:34 +02:00
#include "GameStateSnapshots.h"
#include "Input.h"
2018-06-22 23:25:16 +02:00
#include "OpenRCT2.h"
#include "ParkImporter.h"
#include "PlatformEnvironment.h"
#include "ReplayManager.h"
2018-06-22 23:25:16 +02:00
#include "Version.h"
2026-02-09 15:07:42 +01:00
#include "actions/GameActionRunner.h"
2025-02-17 07:24:03 -05:00
#include "audio/Audio.h"
2018-06-22 23:25:16 +02:00
#include "audio/AudioContext.h"
#include "config/Config.h"
2017-03-26 21:04:14 +01:00
#include "core/Console.hpp"
#include "core/File.h"
2017-06-26 22:00:01 +01:00
#include "core/FileScanner.h"
#include "core/FileStream.h"
2017-03-26 21:04:14 +01:00
#include "core/Guard.hpp"
#include "core/Http.h"
2017-06-06 23:42:28 +01:00
#include "core/MemoryStream.h"
2017-06-26 22:00:01 +01:00
#include "core/Path.hpp"
2017-03-26 21:04:14 +01:00
#include "core/String.hpp"
2021-12-02 17:28:59 +02:00
#include "core/Timer.hpp"
2026-01-13 23:41:59 +01:00
#include "drawing/ColourMap.h"
#include "drawing/Drawing.h"
#include "drawing/IDrawingEngine.h"
2021-12-07 20:55:27 +00:00
#include "drawing/Image.h"
2018-01-08 16:22:45 +01:00
#include "drawing/LightFX.h"
2021-11-24 17:19:52 +02:00
#include "entity/EntityTweener.h"
#include "entity/PatrolArea.h"
2018-01-05 23:00:39 +00:00
#include "interface/Chat.h"
#include "interface/StdInOutConsole.h"
2018-03-13 13:14:02 +01:00
#include "interface/Viewport.h"
2021-12-11 18:06:06 -05:00
#include "localisation/Formatter.h"
#include "localisation/Localisation.Date.h"
2018-04-24 13:18:05 +01:00
#include "localisation/LocalisationService.h"
2017-11-10 20:23:23 +00:00
#include "network/DiscordService.h"
2025-02-24 04:43:06 -05:00
#include "network/Network.h"
2021-08-17 06:20:07 +03:00
#include "network/NetworkBase.h"
2018-06-22 23:25:16 +02:00
#include "object/ObjectManager.h"
#include "object/ObjectRepository.h"
#include "paint/Painter.h"
2022-04-23 14:45:15 +01:00
#include "park/ParkFile.h"
2018-06-22 23:25:16 +02:00
#include "platform/Crash.h"
2022-02-18 21:57:00 +01:00
#include "platform/Platform.h"
2022-01-18 10:21:20 -08:00
#include "profiling/Profiling.h"
2023-12-10 19:35:17 +01:00
#include "rct2/RCT2.h"
2018-06-22 23:25:16 +02:00
#include "ride/TrackDesignRepository.h"
#include "scenario/Scenario.h"
2018-06-22 23:25:16 +02:00
#include "scenario/ScenarioRepository.h"
2026-06-14 18:46:48 +02:00
#include "scenes/SceneManager.h"
#include "scenes/editor/EditorScene.h"
#include "scenes/game/GameScene.h"
2024-04-26 20:35:16 +02:00
#include "scenes/intro/IntroScene.h"
#include "scenes/preloader/PreloaderScene.h"
#include "scenes/title/TitleScene.h"
#include "scenes/title/TitleSequenceManager.h"
2018-03-18 23:35:58 +00:00
#include "scripting/HookEngine.h"
#include "scripting/ScriptEngine.h"
2018-06-22 23:25:16 +02:00
#include "ui/UiContext.h"
#include "ui/WindowManager.h"
#include "world/MapAnimation.h"
#include "world/MapSelection.h"
#include <chrono>
2018-11-21 23:16:04 +01:00
#include <cmath>
#include <exception>
2020-07-21 23:22:48 +02:00
#include <future>
2018-11-21 23:16:04 +01:00
#include <iterator>
#include <memory>
#include <string>
using namespace OpenRCT2;
2017-03-25 03:16:40 +00:00
using namespace OpenRCT2::Ui;
using OpenRCT2::Audio::IAudioContext;
2017-03-25 03:16:40 +00:00
namespace OpenRCT2
{
namespace
{
using namespace std::chrono_literals;
static constexpr auto kForcedUpdateInterval = 25ms;
} // namespace
class Context final : public IContext
{
2017-03-25 03:16:40 +00:00
private:
2017-03-26 21:04:14 +01:00
// Dependencies
std::unique_ptr<IPlatformEnvironment> const _env;
std::unique_ptr<IAudioContext> const _audioContext;
std::unique_ptr<IUiContext> const _uiContext;
2017-03-26 21:04:14 +01:00
// Services
std::unique_ptr<Localisation::LocalisationService> _localisationService;
std::unique_ptr<IObjectRepository> _objectRepository;
std::unique_ptr<IObjectManager> _objectManager;
std::unique_ptr<ITrackDesignRepository> _trackDesignRepository;
std::unique_ptr<IScenarioRepository> _scenarioRepository;
2026-06-14 18:46:48 +02:00
std::unique_ptr<ISceneManager> _sceneManager;
std::unique_ptr<IReplayManager> _replayManager;
2019-05-11 21:31:34 +02:00
std::unique_ptr<IGameStateSnapshots> _gameStateSnapshots;
2022-09-18 16:15:42 +01:00
std::unique_ptr<AssetPackManager> _assetPackManager;
2017-11-10 20:23:23 +00:00
#ifdef __ENABLE_DISCORD__
std::unique_ptr<Network::DiscordService> _discordService;
2017-11-10 20:23:23 +00:00
#endif
2018-06-22 23:25:16 +02:00
StdInOutConsole _stdInOutConsole;
#ifdef ENABLE_SCRIPTING
Scripting::ScriptEngine _scriptEngine;
2020-02-23 12:55:48 +00:00
#endif
2021-08-17 06:20:07 +03:00
#ifndef DISABLE_NETWORK
Network::NetworkBase _network;
2021-08-17 06:20:07 +03:00
#endif
2017-03-26 21:04:14 +01:00
DrawingEngine _drawingEngineType = DrawingEngine::SoftwareWithHardwareDisplay;
std::unique_ptr<Drawing::IDrawingEngine> _drawingEngine;
std::unique_ptr<Paint::Painter> _painter;
2018-06-22 23:25:16 +02:00
bool _initialised = false;
2021-12-02 17:28:59 +02:00
Timer _timer;
2021-12-02 17:57:18 +02:00
float _ticksAccumulator = 0.0f;
float _realtimeAccumulator = 0.0f;
float _timeScale = 1.0f;
2018-06-22 23:25:16 +02:00
bool _variableFrame = false;
2017-03-26 21:04:14 +01:00
2021-01-10 18:23:35 +00:00
// If set, will end the OpenRCT2 game loop. Intentionally private to this module so that the flag can not be set back to
// false.
2017-03-26 21:04:14 +01:00
bool _finished = false;
2020-07-21 23:22:48 +02:00
std::future<void> _versionCheckFuture;
NewVersionInfo _newVersionInfo;
bool _hasNewVersionInfo = false;
// We keep track of this to perform certain operations differently.
std::thread::id _mainThreadId{};
Timer _forcedUpdateTimer;
2025-04-05 17:36:25 +03:00
BackgroundWorker _backgroundWorker;
2017-03-25 03:16:40 +00:00
public:
// Singleton of Context.
// Remove this when GetContext() is no longer called so that
// multiple instances can be created in parallel
2018-06-22 23:25:16 +02:00
static Context* Instance;
2017-03-25 03:16:40 +00:00
public:
2018-04-20 19:58:59 +01:00
Context(
std::unique_ptr<IPlatformEnvironment>&& env, std::unique_ptr<IAudioContext>&& audioContext,
std::unique_ptr<IUiContext>&& uiContext)
: _env(std::move(env))
, _audioContext(std::move(audioContext))
, _uiContext(std::move(uiContext))
, _localisationService(std::make_unique<Localisation::LocalisationService>(*_env))
2024-04-23 19:52:52 +02:00
, _replayManager(CreateReplayManager())
, _gameStateSnapshots(CreateGameStateSnapshots())
#ifdef ENABLE_SCRIPTING
, _scriptEngine(_stdInOutConsole, *_env)
2021-08-17 06:20:07 +03:00
#endif
#ifndef DISABLE_NETWORK
, _network(*this)
2020-02-23 12:55:48 +00:00
#endif
, _painter(std::make_unique<Paint::Painter>(*_uiContext))
2017-03-24 19:02:23 +00:00
{
// Can't have more than one context currently.
Guard::Assert(Instance == nullptr);
2017-03-25 03:16:40 +00:00
Instance = this;
_mainThreadId = std::this_thread::get_id();
2017-03-24 19:02:23 +00:00
}
2017-03-25 03:16:40 +00:00
~Context() override
{
2018-12-17 12:58:12 +01:00
// NOTE: We must shutdown all systems here before Instance is set back to null.
// If objects use GetContext() in their destructor things won't go well.
2022-02-27 15:48:43 +00:00
#ifdef ENABLE_SCRIPTING
_scriptEngine.StopUnloadRegisterAllPlugins();
#endif
GameActions::ClearQueue();
_replayManager->StopRecording(true);
2021-08-17 10:36:18 +03:00
#ifndef DISABLE_NETWORK
2021-08-17 06:20:07 +03:00
_network.Close();
2021-08-17 10:36:18 +03:00
#endif
auto* windowMgr = GetWindowManager();
2025-09-29 02:05:00 +10:00
windowMgr->Cleanup();
// Unload objects after closing all windows, this is to overcome windows like
// the object selection window which loads objects when closed.
if (_objectManager != nullptr)
2018-08-29 13:46:56 +02:00
{
_objectManager->UnloadAll();
}
GfxObjectCheckAllImagesFreed();
GfxUnloadCsg();
GfxUnloadG2PalettesFontsTracks();
GfxUnloadG1();
2021-01-09 20:54:02 +00:00
Audio::Close();
2017-03-25 03:16:40 +00:00
Instance = nullptr;
}
IAudioContext& GetAudioContext() override
2017-03-28 19:58:15 +01:00
{
return *_audioContext;
2017-03-28 19:58:15 +01:00
}
IUiContext& GetUiContext() override
2017-03-25 03:16:40 +00:00
{
return *_uiContext;
2017-03-25 03:16:40 +00:00
}
#ifdef ENABLE_SCRIPTING
Scripting::ScriptEngine& GetScriptEngine() override
{
return _scriptEngine;
}
2020-02-23 12:55:48 +00:00
#endif
IPlatformEnvironment& GetPlatformEnvironment() override
{
return *_env;
}
Localisation::LocalisationService& GetLocalisationService() override
2018-04-24 13:18:05 +01:00
{
return *_localisationService;
2018-04-24 13:18:05 +01:00
}
2018-08-29 00:52:10 +02:00
IObjectManager& GetObjectManager() override
{
2018-08-29 00:52:10 +02:00
return *_objectManager;
}
2018-08-29 00:52:10 +02:00
IObjectRepository& GetObjectRepository() override
{
2018-08-29 00:52:10 +02:00
return *_objectRepository;
}
2018-06-22 23:25:16 +02:00
ITrackDesignRepository* GetTrackDesignRepository() override
{
return _trackDesignRepository.get();
}
2018-06-22 23:25:16 +02:00
IScenarioRepository* GetScenarioRepository() override
{
return _scenarioRepository.get();
}
2026-06-14 18:46:48 +02:00
ISceneManager* GetSceneManager() override
{
return _sceneManager.get();
}
IReplayManager* GetReplayManager() override
{
return _replayManager.get();
}
2019-05-11 21:31:34 +02:00
IGameStateSnapshots* GetGameStateSnapshots() override
{
return _gameStateSnapshots.get();
}
2022-09-18 16:15:42 +01:00
AssetPackManager* GetAssetPackManager() override
{
return _assetPackManager.get();
}
DrawingEngine GetDrawingEngineType() override
{
return _drawingEngineType;
}
Drawing::IDrawingEngine* GetDrawingEngine() override
{
return _drawingEngine.get();
}
2021-08-17 06:20:07 +03:00
Paint::Painter* GetPainter() override
2019-02-19 16:03:08 +01:00
{
return _painter.get();
}
2021-08-17 06:20:07 +03:00
#ifndef DISABLE_NETWORK
Network::NetworkBase& GetNetwork() override
2021-08-17 06:20:07 +03:00
{
return _network;
}
#endif
2018-06-22 23:25:16 +02:00
int32_t RunOpenRCT2(int argc, const char** argv) override
2017-03-25 03:16:40 +00:00
{
if (Initialise())
{
Launch();
2019-10-05 12:57:07 -04:00
return EXIT_SUCCESS;
}
2019-10-05 12:57:07 -04:00
return EXIT_FAILURE;
2017-03-25 03:16:40 +00:00
}
2017-03-26 21:04:14 +01:00
2018-06-22 23:25:16 +02:00
void WriteLine(const std::string& s) override
2018-03-11 22:25:34 +00:00
{
_stdInOutConsole.WriteLine(s);
}
2021-02-13 00:15:27 +00:00
void WriteErrorLine(const std::string& s) override
{
_stdInOutConsole.WriteLineError(s);
}
2017-03-26 21:04:14 +01:00
/**
* Causes the OpenRCT2 game loop to finish.
*/
2017-05-06 22:53:51 +02:00
void Finish() override
2017-03-26 21:04:14 +01:00
{
_finished = true;
}
2017-07-28 18:43:48 +01:00
void Quit() override
{
2025-03-01 15:48:02 +01:00
gSavePromptMode = PromptMode::quit;
ContextOpenWindow(WindowClass::savePrompt);
2017-07-28 18:43:48 +01:00
}
2017-06-03 23:10:20 +01:00
bool Initialise() final override
2017-03-26 21:04:14 +01:00
{
if (_initialised)
{
throw std::runtime_error("Context already initialised.");
}
_initialised = true;
2023-01-17 20:46:55 +01:00
CrashInit();
2017-03-26 21:04:14 +01:00
2025-10-07 20:14:37 +02:00
if (String::equals(Config::Get().general.lastRunVersion, kOpenRCT2Version))
2017-03-26 21:04:14 +01:00
{
gOpenRCT2ShowChangelog = false;
}
else
{
gOpenRCT2ShowChangelog = true;
2025-10-07 20:14:37 +02:00
Config::Get().general.lastRunVersion = kOpenRCT2Version;
2024-05-10 12:10:21 +02:00
Config::Save();
2017-03-26 21:04:14 +01:00
}
try
{
2025-10-07 20:14:37 +02:00
_localisationService->OpenLanguage(Config::Get().general.language);
}
catch (const std::exception& e)
{
LOG_ERROR("Failed to open configured language: %s", e.what());
try
{
_localisationService->OpenLanguage(LANGUAGE_ENGLISH_UK);
}
catch (const std::exception& eFallback)
{
LOG_FATAL("Failed to open fallback language: %s", eFallback.what());
auto& uiContext = GetContext()->GetUiContext();
#ifdef __ANDROID__
uiContext.ShowMessageBox(
"You need to copy some additional files to finish your install.\n\nSee "
"https://docs.openrct2.io/en/latest/installing/installing-on-android.html for more details.");
#else
uiContext.ShowMessageBox("Failed to load language file!\nYour installation may be damaged.");
#endif
return false;
}
}
// TODO add configuration option to allow multiple instances
2022-02-18 21:57:00 +01:00
// if (!gOpenRCT2Headless && !Platform::LockSingleInstance()) {
// LOG_FATAL("OpenRCT2 is already running.");
// return false;
// } //This comment was relocated so it would stay where it was in relation to the following lines of code.
2018-02-10 21:43:26 +00:00
if (!gOpenRCT2Headless)
{
2018-02-10 21:43:26 +00:00
auto rct2InstallPath = GetOrPromptRCT2Path();
if (rct2InstallPath.empty())
{
return false;
}
2025-03-25 22:27:57 +01:00
_env->SetBasePath(DirBase::rct2, rct2InstallPath);
}
// The repositories are all dependent on the RCT2 path being set,
// so they cannot be set in the constructor.
_objectRepository = CreateObjectRepository(*_env);
_objectManager = CreateObjectManager(*_objectRepository);
_trackDesignRepository = CreateTrackDesignRepository(*_env);
_scenarioRepository = CreateScenarioRepository(*_env);
2026-06-14 18:46:48 +02:00
_sceneManager = createSceneManager(this);
2022-09-18 16:15:42 +01:00
if (!gOpenRCT2Headless)
{
_assetPackManager = std::make_unique<AssetPackManager>();
}
2017-11-10 20:23:23 +00:00
#ifdef __ENABLE_DISCORD__
if (!gOpenRCT2Headless)
{
_discordService = std::make_unique<Network::DiscordService>();
}
2017-11-10 20:23:23 +00:00
#endif
2026-01-05 15:03:44 +01:00
#ifndef __HAIKU__ // Haiku's user is always root, skip warning them about it.
2022-01-10 13:02:11 +01:00
if (Platform::ProcessIsElevated())
{
2018-04-24 13:18:05 +01:00
std::string elevationWarning = _localisationService->GetString(STR_ADMIN_NOT_RECOMMENDED);
if (gOpenRCT2Headless)
{
Console::Error::WriteLine(elevationWarning.c_str());
}
else
{
_uiContext->ShowMessageBox(elevationWarning);
}
}
2026-01-05 15:03:44 +01:00
#endif
if (Platform::IsRunningInWine())
{
std::string wineWarning = _localisationService->GetString(STR_WINE_NOT_RECOMMENDED);
if (gOpenRCT2Headless)
{
Console::Error::WriteLine(wineWarning.c_str());
}
else
{
_uiContext->ShowMessageBox(wineWarning);
}
}
2017-03-26 21:04:14 +01:00
if (!gOpenRCT2Headless)
{
2017-06-25 23:45:19 +01:00
_uiContext->CreateWindow();
2017-03-26 21:04:14 +01:00
}
EnsureUserContentDirectoriesExist();
2017-03-26 21:04:14 +01:00
if (!gOpenRCT2Headless)
{
Audio::Init();
Audio::PopulateDevices();
Audio::InitRideSoundsAndInfo();
2025-10-07 20:14:37 +02:00
Audio::gGameSoundsOff = !Config::Get().sound.masterSoundEnabled;
2017-03-26 21:04:14 +01:00
}
2023-01-16 21:14:50 +01:00
ChatInit();
2017-06-26 22:00:01 +01:00
CopyOriginalUserFilesOver();
2017-03-26 21:04:14 +01:00
if (!gOpenRCT2NoGraphics)
2017-03-26 21:04:14 +01:00
{
if (!LoadBaseGraphics())
{
return false;
}
Drawing::LightFx::Init();
2017-03-26 21:04:14 +01:00
}
ContextInit();
ResetSubsystems();
if (!gOpenRCT2Headless)
{
2026-06-14 18:46:48 +02:00
auto* preloaderScene = static_cast<PreloaderScene*>(_sceneManager->getPreloaderScene());
_sceneManager->setActiveScene(preloaderScene);
// TODO: preload the title scene in another (parallel) job.
preloaderScene->AddJob([this]() { InitialiseRepositories(); });
}
else
{
InitialiseRepositories();
}
2026-05-17 01:26:29 +10:00
#ifdef ENABLE_SCRIPTING
// quickjs script engine is single-threaded and must be set up on the main thread
_scriptEngine.Initialise();
_uiContext->InitialiseScriptExtensions();
#endif
2017-03-26 21:04:14 +01:00
return true;
}
/**
* rct2: 0x006E6EAC
*/
void ResetSubsystems() override
{
if (!gOpenRCT2NoGraphics)
{
2026-01-13 23:41:59 +01:00
Drawing::initColourMaps();
}
WindowInitAll();
gInputFlags.clearAll();
InputSetState(InputState::reset);
gPressedWidget.windowClassification = WindowClass::null;
gPickupPeepImage = ImageId();
ResetTooltipNotShown();
gMapSelectFlags.clearAll();
ClearPatrolAreaToRender();
TextinputCancel();
}
private:
void InitialiseRepositories()
{
if (!_initialised)
{
throw std::runtime_error("Context needs to be initialised first.");
}
auto currentLanguage = _localisationService->GetCurrentLanguage();
OpenProgress(STR_CHECKING_OBJECT_FILES);
_objectRepository->LoadOrConstruct(currentLanguage);
// Asset packs need to be loaded before any of the objects they may override are.
// This is especially important to keep in mind with intransient objects like Audio objects,
// which are only loaded once.
if (!gOpenRCT2Headless)
{
OpenProgress(STR_CHECKING_ASSET_PACKS);
_assetPackManager->Scan();
_assetPackManager->LoadEnabledAssetPacks();
_assetPackManager->Reload();
}
OpenProgress(STR_LOADING_GENERIC);
Audio::LoadAudioObjects();
OpenProgress(STR_CHECKING_TRACK_DESIGN_FILES);
_trackDesignRepository->Scan(currentLanguage);
OpenProgress(STR_CHECKING_SCENARIO_FILES);
_scenarioRepository->Scan(currentLanguage);
OpenProgress(STR_CHECKING_TITLE_SEQUENCES);
TitleSequenceManager::Scan();
OpenProgress(STR_LOADING_GENERIC);
}
public:
void InitialiseDrawingEngine() final override
{
assert(_drawingEngine == nullptr);
const auto initializeEngine = [&](DrawingEngine engine) -> std::unique_ptr<Drawing::IDrawingEngine> {
try
{
auto drawingEngineFactory = _uiContext->GetDrawingEngineFactory();
auto drawingEngine = drawingEngineFactory->Create(engine, *_uiContext);
if (drawingEngine == nullptr)
{
LOG_FATAL("Unable to create a drawing engine.");
return nullptr;
}
drawingEngine->Initialise();
2025-10-07 20:14:37 +02:00
drawingEngine->SetVSync(Config::Get().general.useVSync);
return drawingEngine;
}
catch (std::exception& ex)
{
LOG_ERROR(ex.what());
LOG_ERROR("Unable to initialise drawing engine.");
}
return nullptr;
};
2025-10-07 20:14:37 +02:00
auto drawingEngineType = Config::Get().general.drawingEngine;
// Attempt to create drawing engine of the type specified in the config.
{
2025-05-02 01:11:24 +03:00
auto drawingEngine = initializeEngine(drawingEngineType);
if (drawingEngine != nullptr)
{
_drawingEngine = std::move(drawingEngine);
}
else
{
// If the drawing engine creation failed, try to create a software engine.
if (drawingEngineType == DrawingEngine::OpenGL)
{
drawingEngineType = DrawingEngine::SoftwareWithHardwareDisplay;
LOG_ERROR("Trying fallback back to software...");
2025-05-02 01:11:24 +03:00
drawingEngine = initializeEngine(drawingEngineType);
if (drawingEngine != nullptr)
{
_drawingEngine = std::move(drawingEngine);
}
else
{
LOG_FATAL("Unable to create any renderer.");
exit(-1);
}
}
}
}
2025-05-02 01:11:24 +03:00
_drawingEngineType = drawingEngineType;
2025-10-07 20:14:37 +02:00
Config::Get().general.drawingEngine = drawingEngineType;
Config::Save();
WindowCheckAllValidZoom();
}
void DisposeDrawingEngine() final override
{
_drawingEngine = nullptr;
}
void OpenProgress(StringId captionStringId) override
2024-05-06 14:26:00 +00:00
{
auto captionString = _localisationService->GetString(captionStringId);
auto intent = Intent(INTENT_ACTION_PROGRESS_OPEN);
intent.PutExtra(INTENT_EXTRA_MESSAGE, captionString);
ContextOpenIntent(&intent);
}
2024-05-06 14:26:00 +00:00
2025-01-19 16:59:45 +01:00
void SetProgress(uint32_t currentProgress, uint32_t totalCount, StringId format = kStringIdNone) override
{
if (_forcedUpdateTimer.GetElapsedTime() < kForcedUpdateInterval)
return;
_forcedUpdateTimer.Restart();
auto intent = Intent(INTENT_ACTION_PROGRESS_SET);
intent.PutExtra(INTENT_EXTRA_PROGRESS_OFFSET, currentProgress);
intent.PutExtra(INTENT_EXTRA_PROGRESS_TOTAL, totalCount);
intent.PutExtra(INTENT_EXTRA_STRING_ID, format);
ContextOpenIntent(&intent);
// When we call this from the main thread we can pump messages and redraw.
const auto isMainThread = _mainThreadId == std::this_thread::get_id();
if (!gOpenRCT2Headless && isMainThread)
{
_uiContext->ProcessMessages();
auto* windowMgr = GetWindowManager();
windowMgr->InvalidateByClass(WindowClass::progressWindow);
Draw();
}
}
void CloseProgress() override
{
auto intent = Intent(INTENT_ACTION_PROGRESS_CLOSE);
ContextOpenIntent(&intent);
2024-05-06 14:26:00 +00:00
}
bool LoadParkFromFile(const u8string& path, bool loadTitleScreenOnFail = false, bool asScenario = false) final override
2017-07-02 19:10:22 +01:00
{
LOG_VERBOSE("Context::LoadParkFromFile(%s)", path.c_str());
2022-08-04 19:45:48 +02:00
struct CrashAdditionalFileRegistration
2022-08-04 19:45:48 +02:00
{
CrashAdditionalFileRegistration(const std::string& path)
2022-08-04 19:45:48 +02:00
{
// Register the file for crash upload if it asserts while loading.
2023-01-17 20:46:55 +01:00
CrashRegisterAdditionalFile("load_park", path);
}
~CrashAdditionalFileRegistration()
{
// Deregister park file in case it was processed without hitting an assert.
2023-01-17 20:46:55 +01:00
CrashUnregisterAdditionalFile("load_park");
2022-08-04 19:45:48 +02:00
}
} crash_additional_file_registration(path);
2022-08-04 19:45:48 +02:00
2018-01-18 11:48:53 +01:00
try
{
2024-12-11 22:28:31 +01:00
if (String::iequals(Path::GetExtension(path), ".sea"))
2020-07-09 22:33:45 +01:00
{
auto data = DecryptSea(fs::u8path(path));
2025-07-02 19:41:26 +02:00
auto ms = MemoryStream(data.data(), data.size(), MemoryAccess::read);
2021-10-27 14:21:14 +02:00
if (!LoadParkFromStream(&ms, path, loadTitleScreenOnFail, asScenario))
{
throw std::runtime_error(".sea file may have been renamed.");
}
return true;
2020-07-09 22:33:45 +01:00
}
2021-09-15 22:22:15 +02:00
2025-03-25 18:23:36 +01:00
auto fs = FileStream(path, FileMode::open);
2021-10-27 14:21:14 +02:00
if (!LoadParkFromStream(&fs, path, loadTitleScreenOnFail, asScenario))
2020-07-09 22:33:45 +01:00
{
2021-09-15 22:22:15 +02:00
return false;
2020-07-09 22:33:45 +01:00
}
2021-09-15 22:22:15 +02:00
return true;
2018-01-18 11:48:53 +01:00
}
2018-06-22 23:25:16 +02:00
catch (const std::exception& e)
2018-01-18 11:48:53 +01:00
{
Console::Error::WriteLine(e.what());
if (loadTitleScreenOnFail)
{
2026-06-14 18:46:48 +02:00
_sceneManager->setActiveScene(_sceneManager->getTitleScene());
}
auto windowManager = _uiContext->GetWindowManager();
2025-01-19 16:59:45 +01:00
windowManager->ShowError(STR_FAILED_TO_LOAD_FILE_CONTAINS_INVALID_DATA, kStringIdNone, {});
2018-01-18 11:48:53 +01:00
}
return false;
2017-07-02 19:10:22 +01:00
}
2021-10-27 14:21:14 +02:00
bool LoadParkFromStream(
IStream* stream, const std::string& path, bool loadTitleScreenFirstOnFail = false,
bool asScenario = false) final override
2017-10-30 07:07:01 -04:00
{
try
2017-10-30 07:07:01 -04:00
{
ClassifiedFileInfo info;
if (!TryClassifyFile(stream, &info))
2017-10-30 07:07:01 -04:00
{
throw std::runtime_error("Unable to detect file type");
}
2017-10-30 07:07:01 -04:00
2025-03-25 18:14:32 +01:00
if (info.Type != FileType::park && info.Type != FileType::savedGame && info.Type != FileType::scenario)
{
throw std::runtime_error("Invalid file type.");
}
2019-05-19 17:44:43 +02:00
std::unique_ptr<IParkImporter> parkImporter;
2025-03-25 18:14:32 +01:00
if (info.Type == FileType::park)
2021-10-27 14:21:14 +02:00
{
parkImporter = ParkImporter::CreateParkFile(*_objectRepository);
}
else if (info.Version <= kFileTypeS4Cutoff)
{
// Save is an S4 (RCT1 format)
parkImporter = ParkImporter::CreateS4();
}
else
{
// Save is an S6 (RCT2 format)
parkImporter = ParkImporter::CreateS6(*_objectRepository);
}
2018-05-21 00:11:42 +01:00
2024-07-15 01:17:57 +02:00
// Inhibit viewport rendering while we're loading
WindowSetFlagForAllViewports(VIEWPORT_FLAG_RENDERING_INHIBITED, true);
OpenProgress(asScenario ? STR_LOADING_SCENARIO : STR_LOADING_SAVED_GAME);
SetProgress(0, 100, STR_STRING_M_PERCENT);
2025-03-25 18:14:32 +01:00
auto result = parkImporter->LoadFromStream(stream, info.Type == FileType::scenario, false, path.c_str());
SetProgress(10, 100, STR_STRING_M_PERCENT);
// From this point onwards the currently loaded park will be corrupted if loading fails
// so reload the title screen if that happens.
loadTitleScreenFirstOnFail = true;
GameUnloadScripts();
_objectManager->LoadObjects(result.RequiredObjects, true);
SetProgress(90, 100, STR_STRING_M_PERCENT);
MapAnimations::ClearAll();
// TODO: Have a separate GameState and exchange once loaded.
auto& gameState = ::getGameState();
parkImporter->Import(gameState);
SetProgress(100, 100, STR_STRING_M_PERCENT);
2024-07-15 01:17:57 +02:00
// Reset viewport rendering inhibition
WindowSetFlagForAllViewports(VIEWPORT_FLAG_RENDERING_INHIBITED, false);
gScenarioSavePath = path;
gCurrentLoadedPath = path;
gFirstTimeSaving = true;
GameFixSaveVars();
MapAnimations::MarkAllTiles();
EntityTweener::Get().Reset();
gScreenAge = 0;
gLastAutoSaveUpdate = kAutosavePause;
2018-05-21 00:11:42 +01:00
2021-08-17 10:36:18 +03:00
#ifndef DISABLE_NETWORK
bool sendMap = false;
2021-08-17 10:36:18 +03:00
#endif
2025-03-25 18:14:32 +01:00
if (!asScenario && (info.Type == FileType::park || info.Type == FileType::savedGame))
{
2021-08-17 10:36:18 +03:00
#ifndef DISABLE_NETWORK
if (_network.GetMode() == Network::Mode::client)
2018-05-21 00:11:42 +01:00
{
_network.Close();
}
2021-08-17 10:36:18 +03:00
#endif
2026-06-27 14:59:08 +02:00
GameLoadInit(); // NB: calls `setActiveScene`
2021-08-17 10:36:18 +03:00
#ifndef DISABLE_NETWORK
if (_network.GetMode() == Network::Mode::server)
{
sendMap = true;
2017-10-30 07:07:01 -04:00
}
2021-08-17 10:36:18 +03:00
#endif
2017-10-30 07:07:01 -04:00
}
else
{
2024-01-24 22:17:32 +01:00
ScenarioBegin(gameState);
2021-08-17 10:36:18 +03:00
#ifndef DISABLE_NETWORK
if (_network.GetMode() == Network::Mode::server)
{
sendMap = true;
}
if (_network.GetMode() == Network::Mode::client)
{
_network.Close();
}
2021-08-17 10:36:18 +03:00
#endif
2017-10-30 07:07:01 -04:00
}
// This ensures that the newly loaded save reflects the user's
// 'show real names of guests' option, now that it's a global setting
PeepUpdateNames();
2021-08-17 10:36:18 +03:00
#ifndef DISABLE_NETWORK
if (sendMap)
{
_network.ServerSendMap();
}
2021-08-17 10:36:18 +03:00
#endif
#ifdef USE_BREAKPAD
if (_network.GetMode() == Network::Mode::none)
{
StartSilentRecord();
}
#endif
if (result.SemiCompatibleVersion)
{
auto windowManager = _uiContext->GetWindowManager();
auto ft = Formatter();
ft.Add<uint32_t>(result.TargetVersion);
2025-01-19 16:59:45 +01:00
ft.Add<uint32_t>(kParkFileCurrentVersion);
windowManager->ShowError(STR_WARNING_PARK_VERSION_TITLE, STR_WARNING_PARK_VERSION_MESSAGE, ft);
}
else if (HasObjectsThatUseFallbackImages())
{
Console::Error::WriteLine("Park has objects which require RCT1 linked. Fallback images will be used.");
auto windowManager = _uiContext->GetWindowManager();
2025-01-19 16:59:45 +01:00
windowManager->ShowError(STR_PARK_USES_FALLBACK_IMAGES_WARNING, kStringIdEmpty, Formatter());
}
CloseProgress();
return true;
2017-10-30 07:07:01 -04:00
}
catch (const ObjectLoadException& e)
2017-10-30 07:07:01 -04:00
{
2022-05-15 19:58:30 +01:00
Console::Error::WriteLine("Unable to open park: missing objects");
// If loading the SV6 or SV4 failed return to the title screen if requested.
if (loadTitleScreenFirstOnFail)
{
2026-06-14 18:46:48 +02:00
_sceneManager->setActiveScene(_sceneManager->getTitleScene());
}
// The path needs to be duplicated as it's a const here
// which the window function doesn't like
auto intent = Intent(WindowClass::objectLoadError);
2023-01-17 20:46:55 +01:00
intent.PutExtra(INTENT_EXTRA_PATH, path);
intent.PutExtra(INTENT_EXTRA_LIST, const_cast<ObjectEntryDescriptor*>(e.MissingObjects.data()));
intent.PutExtra(INTENT_EXTRA_LIST_COUNT, static_cast<uint32_t>(e.MissingObjects.size()));
auto windowManager = _uiContext->GetWindowManager();
windowManager->OpenIntent(&intent);
2017-10-30 07:07:01 -04:00
}
catch (const UnsupportedRideTypeException&)
{
2022-05-15 19:58:30 +01:00
Console::Error::WriteLine("Unable to open park: unsupported ride types");
// If loading the SV6 or SV4 failed return to the title screen if requested.
if (loadTitleScreenFirstOnFail)
{
2026-06-14 18:46:48 +02:00
_sceneManager->setActiveScene(_sceneManager->getTitleScene());
}
auto windowManager = _uiContext->GetWindowManager();
2025-01-19 16:59:45 +01:00
windowManager->ShowError(STR_FILE_CONTAINS_UNSUPPORTED_RIDE_TYPES, kStringIdNone, {});
}
catch (const UnsupportedVersionException& e)
{
2022-05-15 19:58:30 +01:00
Console::Error::WriteLine("Unable to open park: unsupported park version");
if (loadTitleScreenFirstOnFail)
{
2026-06-14 18:46:48 +02:00
_sceneManager->setActiveScene(_sceneManager->getTitleScene());
}
auto windowManager = _uiContext->GetWindowManager();
Formatter ft;
2025-01-19 16:59:45 +01:00
/*if (e.TargetVersion < kParkFileMinSupportedVersion)
2022-04-23 14:45:15 +01:00
{
ft.Add<uint32_t>(e.TargetVersion);
windowManager->ShowError(STR_ERROR_PARK_VERSION_TITLE, STR_ERROR_PARK_VERSION_TOO_OLD_MESSAGE, ft);
}
2022-04-24 15:51:41 +02:00
else*/
2022-04-23 14:45:15 +01:00
{
if (e.MinVersion == e.TargetVersion)
{
ft.Add<uint32_t>(e.TargetVersion);
2025-01-19 16:59:45 +01:00
ft.Add<uint32_t>(kParkFileCurrentVersion);
windowManager->ShowError(STR_ERROR_PARK_VERSION_TITLE, STR_ERROR_PARK_VERSION_TOO_NEW_MESSAGE_2, ft);
}
else
{
ft.Add<uint32_t>(e.TargetVersion);
ft.Add<uint32_t>(e.MinVersion);
2025-01-19 16:59:45 +01:00
ft.Add<uint32_t>(kParkFileCurrentVersion);
windowManager->ShowError(STR_ERROR_PARK_VERSION_TITLE, STR_ERROR_PARK_VERSION_TOO_NEW_MESSAGE, ft);
}
2022-04-23 14:45:15 +01:00
}
}
catch (const std::exception& e)
{
// If loading the SV6 or SV4 failed return to the title screen if requested.
if (loadTitleScreenFirstOnFail)
{
2026-06-14 18:46:48 +02:00
_sceneManager->setActiveScene(_sceneManager->getTitleScene());
}
Console::Error::WriteLine(e.what());
}
CloseProgress();
2024-07-15 01:17:57 +02:00
WindowSetFlagForAllViewports(VIEWPORT_FLAG_RENDERING_INHIBITED, false);
2017-10-30 07:07:01 -04:00
return false;
}
2017-06-03 23:10:20 +01:00
private:
bool HasObjectsThatUseFallbackImages()
{
2024-03-27 21:26:07 +01:00
for (auto objectType : getAllObjectTypes())
{
auto maxObjectsOfType = static_cast<ObjectEntryIndex>(getObjectEntryGroupCount(objectType));
for (ObjectEntryIndex i = 0; i < maxObjectsOfType; i++)
{
auto obj = _objectManager->GetLoadedObject(objectType, i);
if (obj != nullptr)
{
if (obj->UsesFallbackImages())
return true;
}
}
}
return false;
}
2017-07-28 19:11:12 +01:00
std::string GetOrPromptRCT2Path()
{
auto result = std::string();
2022-01-27 14:21:46 +01:00
if (gCustomRCT2DataPath.empty())
2017-07-28 19:11:12 +01:00
{
// Check install directory
2025-10-07 20:14:37 +02:00
if (Config::Get().general.rct2Path.empty() || !Platform::OriginalGameDataExists(Config::Get().general.rct2Path))
2017-07-28 19:11:12 +01:00
{
LOG_VERBOSE(
2024-05-10 12:10:21 +02:00
"install directory does not exist or invalid directory selected, %s",
2025-10-07 20:14:37 +02:00
Config::Get().general.rct2Path.c_str());
2024-05-10 12:10:21 +02:00
if (!Config::FindOrBrowseInstallDirectory())
2017-07-28 19:11:12 +01:00
{
2024-05-10 12:10:21 +02:00
auto path = Config::GetDefaultPath();
2018-06-22 23:25:16 +02:00
Console::Error::WriteLine(
"An RCT2 install directory must be specified! Please edit \"game_path\" in %s.\n", path.c_str());
2017-07-28 19:11:12 +01:00
return std::string();
}
}
2025-10-07 20:14:37 +02:00
result = Config::Get().general.rct2Path;
2017-07-28 19:11:12 +01:00
}
else
{
2022-01-27 14:21:46 +01:00
result = gCustomRCT2DataPath;
2017-07-28 19:11:12 +01:00
}
return result;
}
// TODO: move function elsewhere?
bool LoadBaseGraphics()
{
if (!GfxLoadG1(*_env))
{
return false;
}
GfxLoadG2PalettesFontsTracks();
GfxLoadCsg();
FontSpriteInitialiseCharacters();
return true;
}
void SwitchToStartUpScene()
2017-03-26 21:04:14 +01:00
{
if (gOpenRCT2Headless)
2017-03-26 21:04:14 +01:00
{
// NONE or OPEN are the only allowed actions for headless mode
if (gOpenRCT2StartupAction != StartupAction::open)
{
gOpenRCT2StartupAction = StartupAction::none;
}
}
else
{
if ((gOpenRCT2StartupAction == StartupAction::title) && Config::Get().general.playIntro)
{
gOpenRCT2StartupAction = StartupAction::intro;
}
2017-03-26 21:04:14 +01:00
}
IScene* nextScene{};
2018-06-22 23:25:16 +02:00
switch (gOpenRCT2StartupAction)
2017-03-26 21:04:14 +01:00
{
case StartupAction::intro:
{
2026-06-14 18:46:48 +02:00
nextScene = _sceneManager->getIntroScene();
break;
}
case StartupAction::title:
{
2026-06-14 18:46:48 +02:00
nextScene = _sceneManager->getTitleScene();
break;
}
case StartupAction::open:
2017-03-26 21:04:14 +01:00
{
2018-06-22 23:25:16 +02:00
// A path that includes "://" is illegal with all common filesystems, so it is almost certainly a URL
// This way all cURL supported protocols, like http, ftp, scp and smb are automatically handled
if (strstr(gOpenRCT2StartupActionPath, "://") != nullptr)
{
2017-03-26 21:04:14 +01:00
#ifndef DISABLE_HTTP
2018-06-22 23:25:16 +02:00
// Download park and open it using its temporary filename
auto data = DownloadPark(gOpenRCT2StartupActionPath);
if (data.empty())
{
2026-06-14 18:46:48 +02:00
nextScene = _sceneManager->getTitleScene();
break;
}
2017-03-26 21:04:14 +01:00
2025-07-02 19:41:26 +02:00
auto ms = MemoryStream(data.data(), data.size(), MemoryAccess::read);
2018-06-22 23:25:16 +02:00
if (!LoadParkFromStream(&ms, gOpenRCT2StartupActionPath, true))
{
Console::Error::WriteLine("Failed to load '%s'", gOpenRCT2StartupActionPath);
2026-06-14 18:46:48 +02:00
nextScene = _sceneManager->getTitleScene();
break;
2018-06-22 23:25:16 +02:00
}
#endif
2017-03-26 21:04:14 +01:00
}
else
{
2018-06-22 23:25:16 +02:00
try
{
if (!LoadParkFromFile(gOpenRCT2StartupActionPath, true))
{
2026-06-14 18:46:48 +02:00
nextScene = _sceneManager->getTitleScene();
break;
2018-06-22 23:25:16 +02:00
}
}
catch (const std::exception& ex)
{
Console::Error::WriteLine("Failed to load '%s'", gOpenRCT2StartupActionPath);
Console::Error::WriteLine("%s", ex.what());
2026-06-14 18:46:48 +02:00
nextScene = _sceneManager->getTitleScene();
break;
2018-06-22 23:25:16 +02:00
}
}
// Successfully loaded a file
2026-06-14 18:46:48 +02:00
nextScene = _sceneManager->getGameScene();
break;
2017-03-26 21:04:14 +01:00
}
case StartupAction::edit:
{
auto* editorScene = static_cast<EditorScene*>(_sceneManager->getEditorScene());
_sceneManager->setActiveScene(editorScene);
2024-12-11 22:28:31 +01:00
if (String::sizeOf(gOpenRCT2StartupActionPath) == 0)
2018-06-22 23:25:16 +02:00
{
nextScene = editorScene;
2018-06-22 23:25:16 +02:00
}
else if (editorScene->LoadLandscape(gOpenRCT2StartupActionPath))
2018-06-22 23:25:16 +02:00
{
nextScene = editorScene;
2018-06-22 23:25:16 +02:00
}
else
{
2026-06-14 18:46:48 +02:00
nextScene = _sceneManager->getTitleScene();
}
break;
}
default:
{
2026-06-14 18:46:48 +02:00
nextScene = _sceneManager->getTitleScene();
}
}
2026-06-14 18:46:48 +02:00
_sceneManager->setActiveScene(nextScene);
InitNetworkGame(nextScene == _sceneManager->getGameScene());
}
void InitNetworkGame(bool isGameScene)
{
if (isGameScene)
{
#ifndef DISABLE_NETWORK
if (gNetworkStart == Network::Mode::server)
{
if (gNetworkStartPort == 0)
{
2025-10-07 20:14:37 +02:00
gNetworkStartPort = Config::Get().network.defaultPort;
}
if (gNetworkStartAddress.empty())
{
2025-10-07 20:14:37 +02:00
gNetworkStartAddress = Config::Get().network.listenAddress;
}
if (gCustomPassword.empty())
{
2025-10-07 20:14:37 +02:00
_network.SetPassword(Config::Get().network.defaultPassword.c_str());
}
else
{
_network.SetPassword(gCustomPassword);
}
_network.BeginServer(gNetworkStartPort, gNetworkStartAddress);
}
else
#endif // DISABLE_NETWORK
{
GameLoadScripts();
GameNotifyMapChanged();
}
2017-03-26 21:04:14 +01:00
}
#ifndef DISABLE_NETWORK
else if (gNetworkStart == Network::Mode::client)
2017-03-26 21:04:14 +01:00
{
if (gNetworkStartPort == 0)
{
2025-10-07 20:14:37 +02:00
gNetworkStartPort = Config::Get().network.defaultPort;
2017-03-26 21:04:14 +01:00
}
_network.BeginClient(gNetworkStartHost, gNetworkStartPort);
2017-03-26 21:04:14 +01:00
}
#endif // DISABLE_NETWORK
}
/**
* Launches the game, after command line arguments have been parsed and processed.
*/
void Launch()
{
if (!_versionCheckFuture.valid())
{
_versionCheckFuture = std::async(std::launch::async, [this] {
_newVersionInfo = GetLatestVersion();
2024-12-11 22:28:31 +01:00
if (!String::startsWith(gVersionInfoTag, _newVersionInfo.tag))
{
_hasNewVersionInfo = true;
}
});
}
if (!gOpenRCT2Headless)
{
2026-06-14 18:46:48 +02:00
_sceneManager->getPreloaderScene()->SetOnComplete([&]() { SwitchToStartUpScene(); });
}
else
{
SwitchToStartUpScene();
}
2024-12-31 09:31:33 -06:00
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop_arg(
[](void* vctx) {
auto ctx = reinterpret_cast<Context*>(vctx);
if (ctx->_finished)
{
emscripten_cancel_main_loop();
}
ctx->RunFrame();
},
this, 0, 1);
#else
2018-03-18 00:31:02 +00:00
_stdInOutConsole.Start();
2017-03-26 21:04:14 +01:00
RunGameLoop();
2024-12-31 09:31:33 -06:00
#endif
2017-03-26 21:04:14 +01:00
}
2021-12-02 17:28:59 +02:00
bool ShouldDraw()
{
2018-06-22 23:25:16 +02:00
if (gOpenRCT2Headless)
return false;
if (_uiContext->IsMinimised())
return false;
return true;
}
2021-12-02 17:28:59 +02:00
bool ShouldRunVariableFrame()
{
if (!ShouldDraw())
return false;
2025-10-07 20:14:37 +02:00
if (!Config::Get().general.uncapFPS)
2021-12-02 17:28:59 +02:00
return false;
if (gGameSpeed > 4)
return false;
return true;
}
2017-03-26 21:04:14 +01:00
/**
2018-06-22 23:25:16 +02:00
* Run the main game loop until the finished flag is set.
*/
2024-12-31 09:31:33 -06:00
#ifndef __EMSCRIPTEN__
2017-03-26 21:04:14 +01:00
void RunGameLoop()
{
2022-01-29 05:29:08 -08:00
PROFILED_FUNCTION();
LOG_VERBOSE("begin openrct2 loop");
2017-03-26 21:04:14 +01:00
_finished = false;
_variableFrame = ShouldRunVariableFrame();
2017-03-26 21:04:14 +01:00
do
{
2017-09-07 13:31:28 +02:00
RunFrame();
2018-06-22 23:25:16 +02:00
} while (!_finished);
LOG_VERBOSE("finish openrct2 loop");
2017-03-26 21:04:14 +01:00
}
2024-12-31 09:31:33 -06:00
#endif // __EMSCRIPTEN__
2017-03-26 21:04:14 +01:00
void RunFrame()
{
2022-01-29 05:29:08 -08:00
PROFILED_FUNCTION();
const auto deltaTime = _timer.GetElapsedTimeAndRestart().count();
2021-12-02 17:28:59 +02:00
// Make sure we catch the state change and reset it.
bool useVariableFrame = ShouldRunVariableFrame();
if (_variableFrame != useVariableFrame)
{
_variableFrame = useVariableFrame;
// Switching from variable to fixed frame requires reseting
// of entity positions back to end of tick positions
auto& tweener = EntityTweener::Get();
tweener.Restore();
tweener.Reset();
}
2021-12-02 17:57:18 +02:00
UpdateTimeAccumulators(deltaTime);
Network::Update();
if (useVariableFrame)
{
2021-12-02 17:28:59 +02:00
RunVariableFrame(deltaTime);
}
else
{
2021-12-02 17:28:59 +02:00
RunFixedFrame(deltaTime);
}
Network::Flush();
}
2021-12-02 17:57:18 +02:00
void UpdateTimeAccumulators(float deltaTime)
{
// Ticks
float scaledDeltaTime = deltaTime * _timeScale;
_ticksAccumulator = std::min(_ticksAccumulator + scaledDeltaTime, kGameUpdateMaxThreshold);
2021-12-02 17:57:18 +02:00
// Real Time.
_realtimeAccumulator = std::min(_realtimeAccumulator + deltaTime, kGameUpdateMaxThreshold);
while (_realtimeAccumulator >= kGameUpdateTimeMS)
2021-12-02 17:57:18 +02:00
{
gCurrentRealTimeTicks++;
_realtimeAccumulator -= kGameUpdateTimeMS;
2021-12-02 17:57:18 +02:00
}
}
2021-12-02 17:28:59 +02:00
void RunFixedFrame(float deltaTime)
2017-03-26 21:04:14 +01:00
{
2022-01-29 05:29:08 -08:00
PROFILED_FUNCTION();
2017-06-25 23:45:19 +01:00
_uiContext->ProcessMessages();
if (_ticksAccumulator < kGameUpdateTimeMS)
{
const auto sleepTimeSec = std::min(kNetworkUpdateTimeMS, kGameUpdateTimeMS - _ticksAccumulator);
2022-02-18 21:57:00 +01:00
Platform::Sleep(static_cast<uint32_t>(sleepTimeSec * 1000.f));
return;
}
while (_ticksAccumulator >= kGameUpdateTimeMS)
{
2021-12-02 17:35:31 +02:00
Tick();
_ticksAccumulator -= kGameUpdateTimeMS;
}
2025-04-05 17:36:25 +03:00
_backgroundWorker.dispatchCompleted();
ContextHandleInput();
WindowUpdateAll();
2021-12-02 17:28:59 +02:00
if (ShouldDraw())
2017-03-26 21:04:14 +01:00
{
2022-01-18 10:21:20 -08:00
Draw();
2017-03-26 21:04:14 +01:00
}
}
2021-12-02 17:28:59 +02:00
void RunVariableFrame(float deltaTime)
2017-03-26 21:04:14 +01:00
{
2022-01-29 05:29:08 -08:00
PROFILED_FUNCTION();
2021-12-02 17:28:59 +02:00
const bool shouldDraw = ShouldDraw();
auto& tweener = EntityTweener::Get();
2017-06-25 23:45:19 +01:00
_uiContext->ProcessMessages();
2017-03-26 21:04:14 +01:00
while (_ticksAccumulator >= kGameUpdateTimeMS)
2017-03-26 21:04:14 +01:00
{
// Get the original position of each sprite
2021-12-02 17:28:59 +02:00
if (shouldDraw)
tweener.PreTick();
2017-03-26 21:04:14 +01:00
2021-12-02 17:35:31 +02:00
Tick();
2017-03-26 21:04:14 +01:00
_ticksAccumulator -= kGameUpdateTimeMS;
2017-03-26 21:04:14 +01:00
// Get the next position of each sprite
2021-12-02 17:28:59 +02:00
if (shouldDraw)
tweener.PostTick();
2017-03-26 21:04:14 +01:00
}
2025-04-05 17:36:25 +03:00
_backgroundWorker.dispatchCompleted();
ContextHandleInput();
WindowUpdateAll();
2021-12-02 17:28:59 +02:00
if (shouldDraw)
{
const float alpha = std::min(_ticksAccumulator / kGameUpdateTimeMS, 1.0f);
tweener.Tween(alpha);
2017-03-26 21:04:14 +01:00
2022-01-18 10:21:20 -08:00
Draw();
}
2017-03-26 21:04:14 +01:00
}
2022-01-18 10:21:20 -08:00
void Draw()
{
PROFILED_FUNCTION();
_drawingEngine->BeginDraw();
_painter->Paint(*_drawingEngine);
_drawingEngine->EndDraw();
}
2021-12-02 17:35:31 +02:00
void Tick()
2017-06-25 23:45:19 +01:00
{
2022-01-18 10:21:20 -08:00
PROFILED_FUNCTION();
2021-12-02 17:28:59 +02:00
// TODO: This variable has been never "variable" in time, some code expects
// this to be 40Hz (25 ms). Refactor this once the UI is decoupled.
gCurrentDeltaTime = static_cast<uint16_t>(kGameUpdateTimeMS * 1000.0f);
2018-01-18 11:48:53 +01:00
if (GameIsNotPaused())
2017-06-25 23:45:19 +01:00
{
gPaletteEffectFrame += gCurrentDeltaTime;
2017-06-25 23:45:19 +01:00
}
DateUpdateRealTimeOfDay();
2017-06-25 23:45:19 +01:00
2026-06-14 18:46:48 +02:00
if (auto* activeScene = _sceneManager->getActiveScene())
activeScene->Tick();
2017-06-25 23:45:19 +01:00
2017-11-10 20:23:23 +00:00
#ifdef __ENABLE_DISCORD__
if (_discordService != nullptr)
{
2021-12-02 17:35:31 +02:00
_discordService->Tick();
2017-11-10 20:23:23 +00:00
}
#endif
2023-01-16 21:14:50 +01:00
ChatUpdate();
#ifdef ENABLE_SCRIPTING
2026-06-14 18:46:48 +02:00
if (auto* activeScene = _sceneManager->getActiveScene(); activeScene != _sceneManager->getPreloaderScene())
{
_scriptEngine.Tick();
}
2020-02-23 12:55:48 +00:00
#endif
_stdInOutConsole.ProcessEvalQueue();
2021-12-02 17:35:31 +02:00
_uiContext->Tick();
2017-06-25 23:45:19 +01:00
}
/**
* Ensure that the custom user content folders are present
*/
void EnsureUserContentDirectoriesExist()
{
EnsureDirectoriesExist(
2025-03-25 22:27:57 +01:00
DirBase::user,
{
2025-03-25 23:39:27 +01:00
DirId::objects,
DirId::saves,
DirId::scenarios,
DirId::trackDesigns,
DirId::landscapes,
DirId::heightmaps,
DirId::plugins,
DirId::themes,
DirId::sequences,
DirId::replayRecordings,
DirId::desyncLogs,
DirId::crashDumps,
});
}
2025-03-25 23:39:27 +01:00
void EnsureDirectoriesExist(const DirBase dirBase, const std::initializer_list<DirId>& dirIds)
{
for (const auto& dirId : dirIds)
{
auto path = _env->GetDirectoryPath(dirBase, dirId);
2023-05-09 21:08:46 +02:00
if (!Path::CreateDirectory(path))
LOG_ERROR("Unable to create directory '%s'.", path.c_str());
}
}
2017-06-26 22:00:01 +01:00
/**
2018-06-22 23:25:16 +02:00
* Copy saved games and landscapes to user directory
*/
2017-06-26 22:00:01 +01:00
void CopyOriginalUserFilesOver()
{
2025-03-25 23:39:27 +01:00
CopyOriginalUserFilesOver(DirId::saves, "*.sv6");
CopyOriginalUserFilesOver(DirId::landscapes, "*.sc6");
2017-06-26 22:00:01 +01:00
}
2025-03-25 23:39:27 +01:00
void CopyOriginalUserFilesOver(DirId dirid, const std::string& pattern)
2017-06-26 22:00:01 +01:00
{
2025-03-25 22:27:57 +01:00
auto src = _env->GetDirectoryPath(DirBase::rct2, dirid);
auto dst = _env->GetDirectoryPath(DirBase::user, dirid);
2017-06-26 22:00:01 +01:00
CopyOriginalUserFilesOver(src, dst, pattern);
}
2018-06-22 23:25:16 +02:00
void CopyOriginalUserFilesOver(const std::string& srcRoot, const std::string& dstRoot, const std::string& pattern)
2017-06-26 22:00:01 +01:00
{
LOG_VERBOSE("CopyOriginalUserFilesOver('%s', '%s', '%s')", srcRoot.c_str(), dstRoot.c_str(), pattern.c_str());
2017-06-26 22:00:01 +01:00
auto scanPattern = Path::Combine(srcRoot, pattern);
auto scanner = Path::ScanDirectory(scanPattern, true);
while (scanner->Next())
{
auto src = std::string(scanner->GetPath());
auto dst = Path::Combine(dstRoot, scanner->GetPathRelative());
auto dstDirectory = Path::GetDirectory(dst);
// Create the directory if necessary
2023-05-09 21:08:46 +02:00
if (!Path::CreateDirectory(dstDirectory))
2017-06-26 22:00:01 +01:00
{
2023-05-09 21:08:46 +02:00
Console::Error::WriteLine("Could not create directory %s.", dstDirectory.c_str());
break;
2017-06-26 22:00:01 +01:00
}
// Only copy the file if it doesn't already exist
if (!File::Exists(dst))
{
Console::WriteLine("Copying '%s' to '%s'", src.c_str(), dst.c_str());
if (!File::Copy(src, dst, false))
{
Console::Error::WriteLine("Failed to copy '%s' to '%s'", src.c_str(), dst.c_str());
}
}
}
}
#ifndef DISABLE_HTTP
std::vector<uint8_t> DownloadPark(const std::string& url)
{
// Download park to buffer in memory
Http::Request request;
request.url = url;
request.method = Http::Method::GET;
Http::Response res;
try
{
res = Do(request);
if (res.status != Http::Status::Ok)
throw std::runtime_error("bad http status");
}
catch (std::exception& e)
{
Console::Error::WriteLine("Failed to download '%s', cause %s", request.url.c_str(), e.what());
return {};
}
std::vector<uint8_t> parkData;
parkData.resize(res.body.size());
std::memcpy(parkData.data(), res.body.c_str(), parkData.size());
return parkData;
}
#endif
2020-07-21 23:22:48 +02:00
bool HasNewVersionInfo() const override
{
return _hasNewVersionInfo;
}
const NewVersionInfo* GetNewVersionInfo() const override
{
return &_newVersionInfo;
}
void SetTimeScale(float newScale) override
{
_timeScale = std::clamp(newScale, kGameMinTimeScale, kGameMaxTimeScale);
}
float GetTimeScale() const override
{
return _timeScale;
}
2025-04-05 17:36:25 +03:00
BackgroundWorker& GetBackgroundWorker() override
{
return _backgroundWorker;
}
2017-03-25 03:16:40 +00:00
};
2018-06-22 23:25:16 +02:00
Context* Context::Instance = nullptr;
2017-03-25 03:16:40 +00:00
2018-04-20 19:58:59 +01:00
std::unique_ptr<IContext> CreateContext()
2017-03-25 03:16:40 +00:00
{
return CreateContext(CreatePlatformEnvironment(), Audio::CreateDummyAudioContext(), CreateDummyUiContext());
2017-03-25 03:16:40 +00:00
}
2018-04-20 19:58:59 +01:00
std::unique_ptr<IContext> CreateContext(
std::unique_ptr<IPlatformEnvironment>&& env, std::unique_ptr<IAudioContext>&& audioContext,
std::unique_ptr<IUiContext>&& uiContext)
2017-03-25 03:16:40 +00:00
{
return std::make_unique<Context>(std::move(env), std::move(audioContext), std::move(uiContext));
2017-03-25 03:16:40 +00:00
}
2018-06-22 23:25:16 +02:00
IContext* GetContext()
2017-03-25 03:16:40 +00:00
{
return Context::Instance;
}
2022-11-06 20:49:07 +00:00
void ContextInit()
{
GetWindowManager()->Init();
}
void ContextResetSubsystems()
{
GetContext()->ResetSubsystems();
}
2022-11-06 20:49:07 +00:00
bool ContextLoadParkFromStream(void* stream)
{
return GetContext()->LoadParkFromStream(static_cast<IStream*>(stream), "");
}
2022-11-06 20:49:07 +00:00
void ContextSetCurrentCursor(CursorID cursor)
{
GetContext()->GetUiContext().SetCursor(cursor);
}
2022-11-06 20:49:07 +00:00
void ContextUpdateCursorScale()
{
2025-10-07 20:14:37 +02:00
GetContext()->GetUiContext().SetCursorScale(static_cast<uint8_t>(std::round(Config::Get().general.windowScale)));
}
2022-11-06 20:49:07 +00:00
void ContextHideCursor()
{
GetContext()->GetUiContext().SetCursorVisible(false);
}
2022-11-06 20:49:07 +00:00
void ContextShowCursor()
{
GetContext()->GetUiContext().SetCursorVisible(true);
}
2022-11-06 20:49:07 +00:00
ScreenCoordsXY ContextGetCursorPosition()
{
return GetContext()->GetUiContext().GetCursorPosition();
}
2022-11-06 20:49:07 +00:00
ScreenCoordsXY ContextGetCursorPositionScaled()
{
2022-11-06 20:49:07 +00:00
auto cursorCoords = ContextGetCursorPosition();
2018-02-01 18:49:14 +01:00
// Compensate for window scaling.
2025-10-07 20:14:37 +02:00
return { static_cast<int32_t>(std::ceil(cursorCoords.x / Config::Get().general.windowScale)),
static_cast<int32_t>(std::ceil(cursorCoords.y / Config::Get().general.windowScale)) };
}
2022-11-06 20:49:07 +00:00
void ContextSetCursorPosition(const ScreenCoordsXY& cursorPosition)
{
GetContext()->GetUiContext().SetCursorPosition(cursorPosition);
}
2022-11-06 20:49:07 +00:00
const CursorState* ContextGetCursorState()
{
return GetContext()->GetUiContext().GetCursorState();
}
2022-11-06 20:49:07 +00:00
const uint8_t* ContextGetKeysState()
{
return GetContext()->GetUiContext().GetKeysState();
}
2022-11-06 20:49:07 +00:00
const uint8_t* ContextGetKeysPressed()
{
return GetContext()->GetUiContext().GetKeysPressed();
}
TextInputSession* ContextStartTextInput(u8string& buffer, size_t maxLength)
{
return GetContext()->GetUiContext().StartTextInput(buffer, maxLength);
}
2022-11-06 20:49:07 +00:00
void ContextStopTextInput()
{
GetContext()->GetUiContext().StopTextInput();
}
2022-11-06 20:49:07 +00:00
bool ContextIsInputActive()
{
return GetContext()->GetUiContext().IsTextInputActive();
}
2022-11-06 20:49:07 +00:00
void ContextTriggerResize()
{
return GetContext()->GetUiContext().TriggerResize();
}
2022-11-06 20:49:07 +00:00
void ContextSetFullscreenMode(int32_t mode)
{
return GetContext()->GetUiContext().SetFullscreenMode(static_cast<FullscreenMode>(mode));
}
2022-11-06 20:49:07 +00:00
void ContextRecreateWindow()
{
GetContext()->GetUiContext().RecreateWindow();
}
2022-11-06 20:49:07 +00:00
int32_t ContextGetWidth()
{
return GetContext()->GetUiContext().GetWidth();
}
2022-11-06 20:49:07 +00:00
int32_t ContextGetHeight()
{
return GetContext()->GetUiContext().GetHeight();
}
2022-11-06 20:49:07 +00:00
bool ContextHasFocus()
{
return GetContext()->GetUiContext().HasFocus();
}
2022-11-06 20:49:07 +00:00
void ContextSetCursorTrap(bool value)
{
GetContext()->GetUiContext().SetCursorTrap(value);
}
WindowBase* ContextOpenWindow(WindowClass wc)
{
auto windowManager = GetWindowManager();
2018-02-01 18:49:14 +01:00
return windowManager->OpenWindow(wc);
}
2025-09-17 23:49:17 +02:00
WindowBase* ContextOpenWindowView(WindowView view)
{
auto windowManager = GetWindowManager();
2025-09-17 23:49:17 +02:00
return windowManager->openView(view);
}
2025-09-17 23:35:10 +02:00
WindowBase* ContextOpenDetailWindow(WindowDetail type, int32_t id)
{
auto windowManager = GetWindowManager();
2025-09-17 23:35:10 +02:00
return windowManager->openDetails(type, id);
}
WindowBase* ContextOpenIntent(Intent* intent)
{
auto windowManager = GetWindowManager();
2018-02-01 18:49:14 +01:00
return windowManager->OpenIntent(intent);
}
2022-11-06 20:49:07 +00:00
void ContextBroadcastIntent(Intent* intent)
{
auto windowManager = GetWindowManager();
2018-02-01 18:49:14 +01:00
windowManager->BroadcastIntent(*intent);
}
2022-11-06 20:49:07 +00:00
void ContextForceCloseWindowByClass(WindowClass windowClass)
{
auto windowManager = GetWindowManager();
2018-02-01 18:49:14 +01:00
windowManager->ForceClose(windowClass);
}
WindowBase* ContextShowError(StringId title, StringId message, const Formatter& args, const bool autoClose /* = false */)
{
auto windowManager = GetWindowManager();
return windowManager->ShowError(title, message, args, autoClose);
}
2022-11-06 20:49:07 +00:00
void ContextHandleInput()
{
auto windowManager = GetWindowManager();
2018-02-01 18:49:14 +01:00
windowManager->HandleInput();
}
2022-11-06 20:49:07 +00:00
void ContextInputHandleKeyboard(bool isTitle)
{
auto windowManager = GetWindowManager();
2018-02-01 18:49:14 +01:00
windowManager->HandleKeyboard(isTitle);
}
2022-11-06 20:49:07 +00:00
void ContextQuit()
{
2018-02-01 18:49:14 +01:00
GetContext()->Quit();
}
u8string ContextOpenCommonFileDialog(FileDialogDesc& desc)
{
try
{
return GetContext()->GetUiContext().ShowFileDialog(desc);
}
2022-03-10 00:12:05 +01:00
catch (const std::exception& ex)
{
LOG_ERROR(ex.what());
2022-03-10 00:12:05 +01:00
return u8string{};
}
}
2018-06-22 23:25:16 +02:00
} // namespace OpenRCT2