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

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

800 lines
23 KiB
C++
Raw Normal View History

2014-04-02 00:31:55 +01:00
/*****************************************************************************
2026-01-05 14:42:59 +01:00
* Copyright (c) 2014-2026 OpenRCT2 developers
2015-10-09 18:22:37 +02:00
*
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
2015-10-09 18:22:37 +02:00
*
2018-06-15 14:07:34 +02:00
* OpenRCT2 is licensed under the GNU General Public License version 3.
2014-04-02 00:31:55 +01:00
*****************************************************************************/
2015-10-09 18:22:37 +02:00
2018-06-22 23:25:16 +02:00
#include "Game.h"
2017-03-26 21:42:07 +01:00
#include "Context.h"
2024-07-09 16:23:31 +02:00
#include "Diagnostic.h"
#include "GameState.h"
2019-05-11 21:31:34 +02:00
#include "GameStateSnapshots.h"
2018-06-22 23:25:16 +02:00
#include "Input.h"
#include "OpenRCT2.h"
2020-03-31 23:12:35 +02:00
#include "PlatformEnvironment.h"
#include "ReplayManager.h"
2026-02-09 15:07:42 +01:00
#include "actions/GameActionRunner.h"
#include "actions/general/GameSetSpeedAction.h"
#include "actions/general/LoadOrQuitAction.h"
2025-02-17 07:24:03 -05:00
#include "audio/Audio.h"
2018-06-22 23:25:16 +02:00
#include "config/Config.h"
2021-02-13 02:50:29 +00:00
#include "core/Console.hpp"
2022-01-08 13:57:29 +01:00
#include "core/File.h"
#include "core/FileScanner.h"
#include "core/FileSystem.hpp"
2020-03-31 23:12:35 +02:00
#include "core/Path.hpp"
#include "core/String.hpp"
#include "drawing/Palette.h"
#include "drawing/ScrollingText.h"
#include "entity/EntityList.h"
2021-11-24 16:58:01 +02:00
#include "entity/EntityRegistry.h"
2022-03-08 00:14:52 +00:00
#include "entity/PatrolArea.h"
2021-11-25 23:47:24 +02:00
#include "entity/Peep.h"
2018-01-05 23:45:53 +00:00
#include "interface/Viewport.h"
#include "interface/WindowTypes.h"
2017-10-05 16:22:37 +02:00
#include "management/Research.h"
2025-02-24 04:43:06 -05:00
#include "network/Network.h"
2022-02-18 21:57:00 +01:00
#include "platform/Platform.h"
#include "rct12/CSStringConverter.h"
2017-12-31 13:21:34 +01:00
#include "ride/Ride.h"
#include "ride/Station.h"
#include "scenario/Scenario.h"
2026-06-14 18:46:48 +02:00
#include "scenes/SceneManager.h"
2020-02-06 23:15:20 +00:00
#include "scripting/ScriptEngine.h"
2018-06-02 00:07:14 +01:00
#include "ui/UiContext.h"
#include "ui/WindowManager.h"
2017-10-19 10:01:05 +02:00
#include "windows/Intent.h"
2017-12-14 10:34:12 +01:00
#include "world/Banner.h"
#include "world/Entrance.h"
2018-01-03 14:56:08 +01:00
#include "world/Map.h"
2024-10-15 22:02:31 +02:00
#include "world/tile_element/SurfaceElement.h"
2018-06-22 23:25:16 +02:00
#include <memory>
2016-01-04 16:22:15 +01:00
using namespace OpenRCT2;
2025-08-07 08:34:26 -05:00
#ifdef __EMSCRIPTEN__
extern "C" {
extern void EmscriptenSaveGame(bool isTrackDesign, bool isAutosave, LoadSaveType type);
2025-08-07 08:34:26 -05:00
extern void EmscriptenResetAutosave();
}
#endif
uint16_t gCurrentDeltaTime;
2018-06-22 23:25:16 +02:00
uint8_t gGamePaused = 0;
uint8_t gGameSpeed = 1;
bool gDoSingleUpdate = false;
2018-06-22 23:25:16 +02:00
float gDayNightCycle = 0;
bool gInUpdateCode = false;
bool gInMapInitCode = false;
std::string gCurrentLoadedPath;
bool gIsAutosave = false;
bool gIsAutosaveLoaded = false;
2014-07-26 10:30:55 +01:00
2017-10-30 07:07:01 -04:00
bool gLoadKeepWindowsOpen = false;
uint32_t gCurrentRealTimeTicks;
2016-09-03 20:25:19 +00:00
2022-03-21 22:56:21 +00:00
#ifdef ENABLE_SCRIPTING
static bool _mapChangedExpected;
#endif
2017-07-22 23:19:09 +00:00
using namespace OpenRCT2;
void GameResetSpeed()
{
auto setSpeedAction = GameActions::GameSetSpeedAction(1);
GameActions::Execute(&setSpeedAction, getGameState());
}
void GameIncreaseGameSpeed()
{
2025-10-07 20:14:37 +02:00
auto newSpeed = std::min(Config::Get().general.debuggingTools ? 5 : 4, gGameSpeed + 1);
if (newSpeed == 5)
newSpeed = 8;
auto setSpeedAction = GameActions::GameSetSpeedAction(newSpeed);
GameActions::Execute(&setSpeedAction, getGameState());
}
void GameReduceGameSpeed()
{
auto newSpeed = std::max(1, gGameSpeed - 1);
if (newSpeed == 7)
newSpeed = 4;
auto setSpeedAction = GameActions::GameSetSpeedAction(newSpeed);
GameActions::Execute(&setSpeedAction, getGameState());
}
2014-04-11 02:42:39 +01:00
/**
2015-10-09 18:22:37 +02:00
*
2014-04-11 02:42:39 +01:00
* rct2: 0x0066B5C0 (part of 0x0066B3E8)
*/
void GameCreateWindows()
2014-04-11 02:42:39 +01:00
{
ContextOpenWindow(WindowClass::mainWindow);
ContextOpenWindow(WindowClass::topToolbar);
ContextOpenWindow(WindowClass::gameStatusBar);
ContextOpenWindow(WindowClass::parkInfoPanel);
ContextOpenWindow(WindowClass::dateInfoPanel);
WindowResizeGui(ContextGetWidth(), ContextGetHeight());
2014-04-11 02:42:39 +01:00
}
void PauseToggle()
{
2017-06-06 23:24:18 +02:00
gGamePaused ^= GAME_PAUSED_NORMAL;
auto* windowMgr = Ui::GetWindowManager();
windowMgr->InvalidateByClass(WindowClass::topToolbar);
2017-11-30 18:19:26 +01:00
if (gGamePaused & GAME_PAUSED_NORMAL)
{
Audio::StopAll();
2017-06-06 23:24:18 +02:00
}
}
2014-08-05 19:15:28 +02:00
bool GameIsPaused()
2016-04-23 13:34:55 +01:00
{
2017-06-06 23:24:18 +02:00
return gGamePaused != 0;
2016-04-23 13:34:55 +01:00
}
bool GameIsNotPaused()
2016-04-23 13:34:55 +01:00
{
2017-06-06 23:24:18 +02:00
return gGamePaused == 0;
2016-04-23 13:34:55 +01:00
}
2014-05-02 22:21:08 +01:00
/**
2014-11-20 18:40:10 +00:00
*
2014-05-02 22:21:08 +01:00
* rct2: 0x0066DC0F
*/
static void LoadLandscape()
2014-05-02 22:21:08 +01:00
{
auto intent = Intent(WindowClass::loadsave);
intent.PutEnumExtra<LoadSaveAction>(INTENT_EXTRA_LOADSAVE_ACTION, LoadSaveAction::load);
intent.PutEnumExtra<LoadSaveType>(INTENT_EXTRA_LOADSAVE_TYPE, LoadSaveType::landscape);
2022-11-06 20:49:07 +00:00
ContextOpenIntent(&intent);
2014-05-02 22:21:08 +01:00
}
void RCT2StringToUTF8Self(char* buffer, size_t length)
{
2017-11-30 18:19:26 +01:00
if (length > 0)
{
2025-10-07 20:29:20 +02:00
auto temp = RCT2StringToUTF8(buffer, RCT2LanguageId::englishUK);
2024-12-11 22:28:31 +01:00
String::safeUtf8Copy(buffer, temp.data(), length);
2017-06-06 23:24:18 +02:00
}
}
static void FixGuestsHeadingToParkCount()
{
uint32_t guestsHeadingToPark = 0;
for (auto* peep : EntityList<Guest>())
{
2026-08-17 23:42:30 +02:00
if (peep->outsideOfPark && peep->state != PeepState::leavingPark)
{
guestsHeadingToPark++;
}
}
2025-08-25 22:25:53 +02:00
auto& park = getGameState().park;
if (park.numGuestsHeadingForPark != guestsHeadingToPark)
{
LOG_VERBOSE(
2025-08-25 22:25:53 +02:00
"Corrected bad amount of guests heading to park: %u -> %u", park.numGuestsHeadingForPark, guestsHeadingToPark);
}
2025-08-25 22:25:53 +02:00
park.numGuestsHeadingForPark = guestsHeadingToPark;
}
2023-10-20 14:22:14 +03:00
static void FixGuestCount()
{
2017-06-06 23:24:18 +02:00
// Recalculates peep count after loading a save to fix corrupted files
2020-06-10 17:54:34 +01:00
uint32_t guestCount = 0;
2023-10-20 14:27:02 +03:00
for (auto guest : EntityList<Guest>())
2017-11-30 18:24:44 +01:00
{
2026-05-30 17:21:37 +03:00
if (!guest->outsideOfPark)
2020-06-10 17:54:34 +01:00
{
2023-10-20 14:27:02 +03:00
guestCount++;
2020-06-10 17:54:34 +01:00
}
2017-11-30 18:24:44 +01:00
}
2015-10-07 20:53:55 +02:00
2025-08-25 22:25:53 +02:00
auto& park = getGameState().park;
if (park.numGuestsInPark != guestCount)
{
LOG_VERBOSE("Corrected bad amount of guests in park: %u -> %u", park.numGuestsInPark, guestCount);
}
2025-08-25 22:25:53 +02:00
park.numGuestsInPark = guestCount;
2023-10-20 14:22:14 +03:00
}
2023-10-20 14:22:14 +03:00
static void FixPeepsWithInvalidRideReference()
{
// Peeps to remove have to be cached here, as removing them from within the loop breaks iteration
2019-02-28 19:28:58 +00:00
std::vector<Peep*> peepsToRemove;
// Fix possibly invalid field values
2021-03-16 11:18:06 +00:00
for (auto peep : EntityList<Guest>())
{
2026-08-17 23:42:30 +02:00
if (peep->currentRideStation.ToUnderlying() >= Limits::kMaxStationsPerRide)
{
2026-08-17 23:42:30 +02:00
const auto srcStation = peep->currentRideStation;
const auto rideIdx = peep->currentRide;
if (rideIdx.IsNull())
{
continue;
}
Ride* ride = GetRide(rideIdx);
if (ride == nullptr)
{
LOG_WARNING("Couldn't find ride %u, resetting ride on peep %u", rideIdx, peep->id);
2026-08-17 23:42:30 +02:00
peep->currentRide = RideId::GetNull();
continue;
}
2026-08-17 23:42:30 +02:00
auto curName = peep->getName();
LOG_WARNING(
"Peep %u (%s) has invalid ride station = %u for ride %u.", peep->id, curName.c_str(), srcStation.ToUnderlying(),
2023-01-27 19:18:44 +02:00
rideIdx);
auto station = RideGetFirstValidStationExit(*ride);
if (station.IsNull())
{
LOG_WARNING("Couldn't find station, removing peep %u", peep->id);
peepsToRemove.push_back(peep);
2018-06-22 23:25:16 +02:00
}
else
{
LOG_WARNING("Amending ride station to %u.", station);
2026-08-17 23:42:30 +02:00
peep->currentRideStation = station;
}
}
}
if (!peepsToRemove.empty())
{
// Some broken saves have broken spatial indexes
getGameState().entities.resetEntitySpatialIndices();
}
for (auto ptr : peepsToRemove)
{
2026-08-17 23:42:30 +02:00
ptr->remove();
}
2023-10-20 14:22:14 +03:00
}
2023-10-20 14:22:14 +03:00
static void FixInvalidSurfaces()
{
2017-06-06 23:24:18 +02:00
// Fixes broken saves where a surface element could be null
// and broken saves with incorrect invisible map border tiles
2023-10-20 14:22:14 +03:00
for (int32_t y = 0; y < kMaximumMapSizeTechnical; y++)
2017-11-30 18:19:26 +01:00
{
for (int32_t x = 0; x < kMaximumMapSizeTechnical; x++)
2017-11-30 18:19:26 +01:00
{
auto* surfaceElement = MapGetSurfaceElementAt(TileCoordsXY{ x, y });
if (surfaceElement == nullptr)
2017-06-06 23:24:18 +02:00
{
LOG_ERROR("Null map element at x = %d and y = %d. Fixing...", x, y);
surfaceElement = TileElementInsert<SurfaceElement>(TileCoordsXYZ{ x, y, 14 }.toCoordsXYZ(), 0b0000);
if (surfaceElement == nullptr)
2017-11-30 18:19:26 +01:00
{
LOG_ERROR("Unable to fix: Map element limit reached.");
2017-06-06 23:24:18 +02:00
return;
}
}
// Fix the invisible border tiles.
// At this point, we can be sure that surfaceElement is not NULL.
auto& gameState = getGameState();
if (x == 0 || x == gameState.mapSize.x - 1 || y == 0 || y == gameState.mapSize.y - 1)
{
2026-05-17 15:21:16 +02:00
surfaceElement->setBaseZ(kMinimumLandZ);
surfaceElement->setClearanceZ(kMinimumLandZ);
surfaceElement->setSlope(0);
surfaceElement->setWaterHeight(0);
}
2017-06-06 23:24:18 +02:00
}
}
2023-10-20 14:22:14 +03:00
}
// OpenRCT2 workaround to recalculate some values which are saved redundantly in the save to fix corrupted files.
// For example recalculate guest count by looking at all the guests instead of trusting the value in the file.
void GameFixSaveVars()
{
FixGuestsHeadingToParkCount();
2023-10-20 14:22:14 +03:00
FixGuestCount();
FixPeepsWithInvalidRideReference();
FixInvalidSurfaces();
2021-10-27 14:21:14 +02:00
ResearchFix();
// Fix banners which share their index
2023-01-29 00:43:59 +02:00
BannerApplyFixes();
// Fix invalid vehicle sprite sizes, thus preventing visual corruption of sprites
FixInvalidVehicleSpriteSizes();
2017-10-31 12:57:40 +01:00
// Fix gParkEntrance locations for which the tile_element no longer exists
2022-10-04 07:38:00 +01:00
ParkEntranceFixLocations();
2021-10-27 14:21:14 +02:00
2022-03-08 00:14:52 +00:00
UpdateConsolidatedPatrolAreas();
MapCountRemainingLandRights();
// Update sprite bounds, rather than relying on stored data
PeepUpdateAllBoundingBoxes();
2015-10-07 20:53:55 +02:00
}
void GameLoadInit()
2015-07-05 09:19:01 -06:00
{
auto* context = GetContext();
IGameStateSnapshots* snapshots = context->GetGameStateSnapshots();
2019-05-11 21:31:34 +02:00
snapshots->Reset();
2026-06-27 14:59:08 +02:00
// TODO: move this to caller sites??
2026-06-14 18:46:48 +02:00
auto* sceneMgr = context->GetSceneManager();
if (sceneMgr->getActiveScene() != sceneMgr->getScenarioEditorScene()) // HACK
sceneMgr->setActiveScene(sceneMgr->getGameScene());
// Invalidate scrolling text cache to prevent stale text from previous park
// being displayed due to pointer value reuse in the cache matching logic
Drawing::ScrollingText::invalidate();
// TODO: move relevant UI calls to UI subproject
2017-10-30 07:07:01 -04:00
if (!gLoadKeepWindowsOpen)
{
ContextResetSubsystems();
GameCreateWindows();
2017-11-02 20:16:30 -04:00
}
else
{
auto* mainWindow = WindowGetMain();
WindowUnfollowSprite(*mainWindow);
2017-10-30 07:07:01 -04:00
}
2014-05-04 16:21:15 +01:00
auto windowManager = context->GetUiContext().GetWindowManager();
auto& gameState = getGameState();
windowManager->SetMainView(gameState.savedView, gameState.savedViewZoom, gameState.savedViewRotation);
2014-05-04 16:21:15 +01:00
if (Network::GetMode() != Network::Mode::client)
2017-06-06 23:24:18 +02:00
{
GameActions::ClearQueue();
2017-06-06 23:24:18 +02:00
}
getGameState().entities.resetEntitySpatialIndices();
ResetAllSpriteQuadrantPlacements();
2017-10-07 01:28:00 +02:00
2017-06-06 23:24:18 +02:00
gWindowUpdateTicks = 0;
gCurrentRealTimeTicks = 0;
2014-05-04 16:21:15 +01:00
Drawing::LoadPalette();
2017-11-30 18:19:26 +01:00
if (!gOpenRCT2Headless)
{
windowManager->BroadcastIntent(Intent(INTENT_ACTION_SET_DEFAULT_SCENERY_CONFIG));
windowManager->BroadcastIntent(Intent(INTENT_ACTION_REFRESH_NEW_RIDES));
windowManager->BroadcastIntent(Intent(INTENT_ACTION_CLEAR_TILE_INSPECTOR_CLIPBOARD));
2017-06-06 23:24:18 +02:00
}
2017-06-06 23:24:18 +02:00
gGameSpeed = 1;
2020-02-22 22:18:22 +00:00
}
2020-02-06 23:15:20 +00:00
void GameLoadScripts()
2020-02-22 22:18:22 +00:00
{
#ifdef ENABLE_SCRIPTING
GetContext()->GetScriptEngine().LoadTransientPlugins();
2020-02-23 12:55:48 +00:00
#endif
2020-02-06 23:15:20 +00:00
}
void GameUnloadScripts()
2020-02-06 23:15:20 +00:00
{
#ifdef ENABLE_SCRIPTING
GetContext()->GetScriptEngine().UnloadTransientPlugins();
2020-02-23 12:55:48 +00:00
#endif
2014-05-04 16:21:15 +01:00
}
void GameNotifyMapChange()
2022-03-21 22:56:21 +00:00
{
#ifdef ENABLE_SCRIPTING
// Ensure we don't get a two lots of change events
if (_mapChangedExpected)
return;
using namespace OpenRCT2::Scripting;
auto& scriptEngine = GetContext()->GetScriptEngine();
auto& hookEngine = scriptEngine.GetHookEngine();
2025-03-26 12:16:47 +01:00
hookEngine.Call(HookType::mapChange, false);
2022-03-21 22:56:21 +00:00
_mapChangedExpected = true;
#endif
}
void GameNotifyMapChanged()
2022-02-20 02:05:24 +00:00
{
#ifdef ENABLE_SCRIPTING
using namespace OpenRCT2::Scripting;
auto& scriptEngine = GetContext()->GetScriptEngine();
auto& hookEngine = scriptEngine.GetHookEngine();
2025-03-26 12:16:47 +01:00
hookEngine.Call(HookType::mapChanged, false);
2022-03-21 22:56:21 +00:00
_mapChangedExpected = false;
2022-02-20 02:05:24 +00:00
#endif
}
2015-12-11 09:38:37 -06:00
/**
2014-06-21 15:50:13 +01:00
*
2015-12-11 09:38:37 -06:00
* rct2: 0x0069E9A7
2015-05-30 10:15:29 +01:00
* Call after a rotation or loading of a save to reset sprite quadrants
2014-06-21 15:50:13 +01:00
*/
void ResetAllSpriteQuadrantPlacements()
2014-11-23 23:03:45 +00:00
{
2025-01-19 16:59:45 +01:00
for (EntityId::UnderlyingType i = 0; i < kMaxEntities; i++)
2017-11-30 18:19:26 +01:00
{
auto* spr = getGameState().entities.getEntity(EntityId::FromUnderlying(i));
if (spr != nullptr && spr->type != EntityType::null)
2017-11-30 18:19:26 +01:00
{
spr->moveTo(spr->getLocation());
2017-06-06 23:24:18 +02:00
}
}
2014-06-21 15:50:13 +01:00
}
void SaveGame()
2014-05-27 23:33:16 +02:00
{
if (!gFirstTimeSaving && !gIsAutosaveLoaded)
2017-11-30 18:19:26 +01:00
{
2025-08-07 08:34:26 -05:00
#ifndef __EMSCRIPTEN__
2022-02-26 17:40:49 +01:00
const auto savePath = Path::WithExtension(gScenarioSavePath, ".park");
SaveGameWithName(savePath);
2025-08-07 08:34:26 -05:00
#else
const auto savePath = Path::WithExtension("save", ".park");
SaveGameWithName(savePath);
EmscriptenSaveGame(false, false, LoadSaveType::park);
2025-08-07 08:34:26 -05:00
#endif
2017-11-30 18:19:26 +01:00
}
else
{
SaveGameAs();
2017-06-06 23:24:18 +02:00
}
2015-08-19 21:54:25 +02:00
}
2017-09-12 00:04:03 +02:00
void SaveGameCmd(u8string_view name /* = {} */)
2018-10-14 22:36:41 +02:00
{
if (name.empty())
2018-10-14 22:36:41 +02:00
{
2022-02-26 17:40:49 +01:00
const auto savePath = Path::WithExtension(gScenarioSavePath, ".park");
SaveGameWithName(savePath);
2018-10-14 22:36:41 +02:00
}
else
{
if (!Platform::IsFilenameValid(name))
{
LOG_ERROR("Cannot save game: filename contains invalid characters.");
return;
}
auto& env = GetContext()->GetPlatformEnvironment();
auto savesDir = fs::canonical(env.GetDirectoryPath(DirBase::user, DirId::saves));
auto savePath = savesDir / fs::u8path(u8string(name) + u8".park");
if (!fs::weakly_canonical(savePath).u8string().starts_with(savesDir.u8string()))
{
LOG_ERROR("Save filename must resolve to a path inside the saves directory.");
return;
}
SaveGameWithName(savePath.u8string());
2018-10-14 22:36:41 +02:00
}
}
void SaveGameWithName(u8string_view name)
2018-10-14 22:36:41 +02:00
{
LOG_VERBOSE("Saving to %s", u8string(name).c_str());
auto& gameState = getGameState();
2025-10-07 20:14:37 +02:00
if (ScenarioSave(gameState, name, Config::Get().general.savePluginData ? 1 : 0))
2018-10-14 22:36:41 +02:00
{
LOG_VERBOSE("Saved to %s", u8string(name).c_str());
gCurrentLoadedPath = name;
gIsAutosaveLoaded = false;
2018-10-14 22:36:41 +02:00
gScreenAge = 0;
}
}
std::unique_ptr<Intent> CreateSaveGameAsIntent()
2015-08-19 21:54:25 +02:00
{
2022-02-26 17:20:07 +01:00
auto name = Path::GetFileNameWithoutExtension(gScenarioSavePath);
2017-09-12 00:04:03 +02:00
auto intent = std::make_unique<Intent>(WindowClass::loadsave);
intent->PutEnumExtra<LoadSaveAction>(INTENT_EXTRA_LOADSAVE_ACTION, LoadSaveAction::save);
intent->PutEnumExtra<LoadSaveType>(INTENT_EXTRA_LOADSAVE_TYPE, LoadSaveType::park);
2023-01-17 20:46:55 +01:00
intent->PutExtra(INTENT_EXTRA_PATH, name);
2017-09-12 00:04:03 +02:00
return intent;
}
void SaveGameAs()
2017-09-12 00:04:03 +02:00
{
#ifdef __EMSCRIPTEN__
EmscriptenResetAutosave();
#endif
auto intent = CreateSaveGameAsIntent();
2022-11-06 20:49:07 +00:00
ContextOpenIntent(intent.get());
2014-05-27 23:33:16 +02:00
}
2025-08-07 08:34:26 -05:00
#ifndef __EMSCRIPTEN__
static void LimitAutosaveCount(const size_t numberOfFilesToKeep, bool processLandscapeFolder)
2016-01-04 16:22:15 +01:00
{
2018-06-22 23:25:16 +02:00
size_t autosavesCount = 0;
2017-06-06 23:24:18 +02:00
size_t numAutosavesToDelete = 0;
2016-01-04 16:22:15 +01:00
auto& environment = GetContext()->GetPlatformEnvironment();
auto folderDirectory = environment.GetDirectoryPath(DirBase::user, DirId::saves);
char const* fileFilter = "autosave_*.park";
2017-11-30 18:19:26 +01:00
if (processLandscapeFolder)
{
folderDirectory = environment.GetDirectoryPath(DirBase::user, DirId::landscapes);
2022-01-24 20:03:20 +01:00
fileFilter = "autosave_*.park";
2017-06-06 23:24:18 +02:00
}
2016-11-13 20:17:49 +01:00
2022-03-10 10:51:34 +01:00
const u8string filter = Path::Combine(folderDirectory, "autosave", fileFilter);
2017-06-06 23:24:18 +02:00
// At first, count how many autosaves there are
2017-11-30 18:19:26 +01:00
{
auto scanner = Path::scanDirectory(filter, false);
while (scanner->next())
{
autosavesCount++;
}
2017-06-06 23:24:18 +02:00
}
2016-11-13 20:17:49 +01:00
2017-06-06 23:24:18 +02:00
// If there are fewer autosaves than the number of files to keep we don't need to delete anything
2017-11-30 18:19:26 +01:00
if (autosavesCount <= numberOfFilesToKeep)
{
2017-06-06 23:24:18 +02:00
return;
}
2016-11-13 20:17:49 +01:00
2022-03-10 10:51:34 +01:00
std::vector<u8string> autosaveFiles;
2017-11-30 18:19:26 +01:00
{
auto scanner = Path::scanDirectory(filter, false);
for (size_t i = 0; i < autosavesCount; i++)
2017-11-30 18:19:26 +01:00
{
if (scanner->next())
2017-11-30 18:19:26 +01:00
{
autosaveFiles.emplace_back(Path::Combine(folderDirectory, "autosave", scanner->getPathRelative()));
2017-11-30 18:19:26 +01:00
}
2017-06-06 23:24:18 +02:00
}
}
2016-01-04 16:22:15 +01:00
std::sort(autosaveFiles.begin(), autosaveFiles.end(), [](const auto& saveFile0, const auto& saveFile1) {
return saveFile0.compare(saveFile1) < 0;
});
2016-01-04 16:22:15 +01:00
2017-06-06 23:24:18 +02:00
// Calculate how many saves we need to delete.
2022-03-10 10:51:34 +01:00
numAutosavesToDelete = autosaveFiles.size() - numberOfFilesToKeep;
2016-11-13 20:17:49 +01:00
2017-12-03 22:38:02 +01:00
for (size_t i = 0; numAutosavesToDelete > 0; i++, numAutosavesToDelete--)
2017-11-30 18:19:26 +01:00
{
2022-03-10 10:51:34 +01:00
if (!File::Delete(autosaveFiles[i]))
{
LOG_WARNING("Failed to delete autosave file: %s", autosaveFiles[i].data());
}
2017-06-06 23:24:18 +02:00
}
2016-01-04 16:22:15 +01:00
}
2015-08-19 21:54:25 +02:00
void GameAutosave()
2015-02-21 11:05:15 +00:00
{
2025-03-25 23:39:27 +01:00
auto subDirectory = DirId::saves;
const char* fileExtension = ".park";
uint32_t saveFlags = 0x80000000;
2025-03-05 21:45:04 +01:00
if (isInEditorMode())
2017-11-30 18:19:26 +01:00
{
2025-03-25 23:39:27 +01:00
subDirectory = DirId::landscapes;
2022-01-24 20:03:20 +01:00
fileExtension = ".park";
2017-06-06 23:24:18 +02:00
saveFlags |= 2;
}
2016-07-23 23:25:13 +02:00
2017-06-06 23:24:18 +02:00
// Retrieve current time
auto currentDate = Platform::GetDateLocal();
auto currentTime = Platform::GetTimeLocal();
2016-07-23 23:25:13 +02:00
2017-06-06 23:24:18 +02:00
utf8 timeName[44];
2018-06-22 23:25:16 +02:00
snprintf(
2018-07-21 13:51:54 +02:00
timeName, sizeof(timeName), "autosave_%04u-%02u-%02u_%02u-%02u-%02u%s", currentDate.year, currentDate.month,
currentDate.day, currentTime.hour, currentTime.minute, currentTime.second, fileExtension);
2015-02-21 11:05:15 +00:00
2025-10-07 20:14:37 +02:00
int32_t autosavesToKeep = Config::Get().general.autosaveAmount;
2025-03-05 21:45:04 +01:00
LimitAutosaveCount(autosavesToKeep - 1, isInEditorMode());
2016-07-23 23:25:13 +02:00
auto& env = GetContext()->GetPlatformEnvironment();
auto autosaveDir = Path::Combine(env.GetDirectoryPath(DirBase::user, subDirectory), u8"autosave");
2023-05-09 21:08:46 +02:00
Path::CreateDirectory(autosaveDir);
auto path = Path::Combine(autosaveDir, timeName);
2022-02-27 22:23:35 +01:00
auto backupFileName = u8string(u8"autosave") + fileExtension + u8".bak";
auto backupPath = Path::Combine(autosaveDir, backupFileName);
if (File::Exists(path))
2017-11-30 18:19:26 +01:00
{
2022-01-08 13:57:29 +01:00
File::Copy(path, backupPath, true);
2017-06-06 23:24:18 +02:00
}
2015-02-21 11:05:15 +00:00
auto& gameState = getGameState();
if (!ScenarioSave(gameState, path, saveFlags))
2021-02-13 00:15:27 +00:00
Console::Error::WriteLine("Could not autosave the scenario. Is the save folder writeable?");
2015-02-21 11:05:15 +00:00
}
2025-08-07 08:34:26 -05:00
#else
void GameAutosave()
{
const auto savePath = Path::WithExtension("save", ".park");
SaveGameWithName(savePath);
EmscriptenSaveGame(false, true, LoadSaveType::park);
2025-08-07 08:34:26 -05:00
}
#endif // __EMSCRIPTEN__
2015-02-21 11:05:15 +00:00
2025-03-01 15:44:57 +01:00
static void GameLoadOrQuitNoSavePromptCallback(ModalResult result, const utf8* path)
{
2025-03-01 15:44:57 +01:00
if (result == ModalResult::ok)
2017-11-30 18:19:26 +01:00
{
GameNotifyMapChange();
GameUnloadScripts();
auto* windowMgr = Ui::GetWindowManager();
windowMgr->CloseByClass(WindowClass::editorObjectSelection);
GameLoadScripts();
GameNotifyMapChanged();
gIsAutosaveLoaded = gIsAutosave;
gFirstTimeSaving = false;
2017-06-06 23:24:18 +02:00
}
}
static void NewGameWindowCallback(const utf8* path)
{
// Closing this will cause a Ride window to pop up, so we have to do this to ensure that
// no windows are open (besides the toolbars and LoadSave window).
auto* windowMgr = Ui::GetWindowManager();
windowMgr->CloseByClass(WindowClass::rideConstruction);
windowMgr->CloseAllExceptClass(WindowClass::loadsave);
GameNotifyMapChange();
GetContext()->LoadParkFromFile(path, false, true);
GameLoadScripts();
GameNotifyMapChanged();
2025-08-07 08:34:26 -05:00
#ifdef __EMSCRIPTEN__
EmscriptenResetAutosave();
#endif
}
2014-05-02 22:21:08 +01:00
/**
2015-10-09 18:22:37 +02:00
*
2014-05-02 22:21:08 +01:00
* rct2: 0x0066DB79
*/
void GameLoadOrQuitNoSavePrompt()
2014-05-02 22:21:08 +01:00
{
auto& gameState = getGameState();
2017-11-30 18:19:26 +01:00
switch (gSavePromptMode)
{
2025-03-01 15:48:02 +01:00
case PromptMode::saveBeforeLoad:
2019-02-21 09:34:30 +00:00
{
auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::closeSavePrompt);
GameActions::Execute(&loadOrQuitAction, gameState);
ToolCancel();
2025-03-05 21:45:04 +01:00
if (gLegacyScene == LegacyScene::scenarioEditor)
2018-06-22 23:25:16 +02:00
{
LoadLandscape();
2018-06-22 23:25:16 +02:00
}
else
{
auto intent = Intent(WindowClass::loadsave);
intent.PutEnumExtra<LoadSaveAction>(INTENT_EXTRA_LOADSAVE_ACTION, LoadSaveAction::load);
intent.PutEnumExtra<LoadSaveType>(INTENT_EXTRA_LOADSAVE_TYPE, LoadSaveType::park);
2024-12-04 20:43:55 +02:00
intent.PutExtra(INTENT_EXTRA_CALLBACK, reinterpret_cast<CloseCallback>(GameLoadOrQuitNoSavePromptCallback));
2022-11-06 20:49:07 +00:00
ContextOpenIntent(&intent);
2018-06-22 23:25:16 +02:00
}
break;
2019-02-21 09:34:30 +00:00
}
2025-03-01 15:48:02 +01:00
case PromptMode::saveBeforeQuit:
2019-02-21 09:34:30 +00:00
{
auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::closeSavePrompt);
GameActions::Execute(&loadOrQuitAction, gameState);
ToolCancel();
if (gInputFlags.has(InputFlag::rightMousePressed))
2018-06-22 23:25:16 +02:00
{
gInputFlags.unset(InputFlag::rightMousePressed);
2018-06-22 23:25:16 +02:00
}
GameResetSpeed();
2018-06-22 23:25:16 +02:00
gFirstTimeSaving = true;
GameNotifyMapChange();
GameUnloadScripts();
2025-08-07 08:34:26 -05:00
#ifdef __EMSCRIPTEN__
EmscriptenResetAutosave();
#endif
2026-06-14 18:46:48 +02:00
auto* sceneMgr = GetContext()->GetSceneManager();
sceneMgr->setActiveScene(sceneMgr->getTitleScene());
2018-06-22 23:25:16 +02:00
break;
2019-02-21 09:34:30 +00:00
}
2025-03-01 15:48:02 +01:00
case PromptMode::saveBeforeNewGame:
{
auto loadOrQuitAction = GameActions::LoadOrQuitAction(GameActions::LoadOrQuitModes::closeSavePrompt);
GameActions::Execute(&loadOrQuitAction, gameState);
ToolCancel();
auto intent = Intent(WindowClass::scenarioSelect);
2024-12-04 20:43:55 +02:00
intent.PutExtra(INTENT_EXTRA_CALLBACK, reinterpret_cast<CloseCallback>(NewGameWindowCallback));
ContextOpenIntent(&intent);
break;
}
2018-06-22 23:25:16 +02:00
default:
GameUnloadScripts();
getGameState().entities.resetAllEntities();
GetContext()->Finish();
2018-06-22 23:25:16 +02:00
break;
2017-06-06 23:24:18 +02:00
}
2014-05-02 22:21:08 +01:00
}
2020-03-31 23:12:35 +02:00
void StartSilentRecord()
2020-03-31 23:12:35 +02:00
{
std::string name = Path::Combine(
GetContext()->GetPlatformEnvironment().GetDirectoryPath(DirBase::user), u8"debug_replay.parkrep");
auto* replayManager = GetContext()->GetReplayManager();
2026-08-05 23:30:07 +02:00
if (replayManager->StartRecording(name, k_MaxReplayTicks, IReplayManager::RecordType::silent))
2020-03-31 23:12:35 +02:00
{
ReplayRecordInfo info;
2020-03-31 23:12:35 +02:00
replayManager->GetCurrentReplayInfo(info);
2022-01-27 14:21:46 +01:00
gSilentRecordingName = info.FilePath;
2020-03-31 23:12:35 +02:00
const char* logFmt = "Silent replay recording started: (%s) %s\n";
Console::WriteLine(logFmt, info.Name.c_str(), info.FilePath.c_str());
2020-03-31 23:12:35 +02:00
}
}
bool StopSilentRecord()
2020-03-31 23:12:35 +02:00
{
auto* replayManager = GetContext()->GetReplayManager();
2020-03-31 23:12:35 +02:00
if (!replayManager->IsRecording() && !replayManager->IsNormalising())
{
return false;
}
ReplayRecordInfo info;
2020-03-31 23:12:35 +02:00
replayManager->GetCurrentReplayInfo(info);
if (replayManager->StopRecording())
{
const char* logFmt = "Replay recording stopped: (%s) %s\n"
" Ticks: %u\n"
" Commands: %u\n"
" Checksums: %u";
Console::WriteLine(logFmt, info.Name.c_str(), info.FilePath.c_str(), info.Ticks, info.NumCommands, info.NumChecksums);
2020-03-31 23:12:35 +02:00
return true;
}
return false;
}
2022-03-07 20:40:48 +00:00
void PrepareMapForSave()
{
2023-01-16 21:14:50 +01:00
ViewportSetSavedView();
2022-03-07 20:40:48 +00:00
#ifdef ENABLE_SCRIPTING
auto& scriptEngine = GetContext()->GetScriptEngine();
auto& hookEngine = scriptEngine.GetHookEngine();
if (hookEngine.HasSubscriptions(Scripting::HookType::mapSave))
2022-03-07 20:40:48 +00:00
{
hookEngine.Call(Scripting::HookType::mapSave, false);
2022-03-07 20:40:48 +00:00
}
#endif
}