OpenTTD Source 20261112-master-gbcbec5e63f
misc_sl.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
11
12#include "saveload.h"
13#include "saveload_error.hpp"
15
18#include "../zoom_func.h"
19#include "../window_gui.h"
20#include "../window_func.h"
21#include "../viewport_func.h"
22#include "../gfx_func.h"
24#include "../fios.h"
25#include "../timer/timer.h"
27
28#include "../safeguards.h"
29
30extern TileIndex _cur_tileloop_tile;
31extern uint16_t _disaster_delay;
32extern uint8_t _trees_tick_ctr;
33
40
41void SaveViewportBeforeSaveGame()
42{
43 /* Don't use GetMainWindow() in case the window does not exist. */
44 const Window *w = FindWindowById(WindowClass::MainWindow, 0);
45 if (w == nullptr || w->viewport == nullptr) {
46 /* Ensure saved position is clearly invalid. */
47 _saved_scrollpos_x = INT_MAX;
48 _saved_scrollpos_y = INT_MAX;
50 } else {
51 _saved_scrollpos_x = w->viewport->scrollpos_x;
52 _saved_scrollpos_y = w->viewport->scrollpos_y;
54 }
55}
56
57void ResetViewportAfterLoadGame()
58{
59 if (_saved_scrollpos_x == INT_MAX && _saved_scrollpos_y == INT_MAX) return;
60
61 Window *w = GetMainWindow();
62
63 w->viewport->scrollpos_x = _saved_scrollpos_x;
64 w->viewport->scrollpos_y = _saved_scrollpos_y;
65 w->viewport->dest_scrollpos_x = _saved_scrollpos_x;
66 w->viewport->dest_scrollpos_y = _saved_scrollpos_y;
67
68 Viewport &vp = *w->viewport;
72
73 /* If zoom_max is ZoomLevel::Min then the setting has not been loaded yet, therefore all levels are allowed. */
74 if (_settings_client.gui.zoom_max != ZoomLevel::Min) {
75 /* Ensure zoom level is allowed */
76 while (vp.zoom < _settings_client.gui.zoom_min) DoZoomInOutWindow(ZOOM_OUT, w);
77 while (vp.zoom > _settings_client.gui.zoom_max) DoZoomInOutWindow(ZOOM_IN, w);
78 }
79
80 DoZoomInOutWindow(ZOOM_NONE, w); // update button status
82}
83
86
87static const SaveLoad _date_desc[] = {
107 /* For older savegames, we load the current value as the "period"; afterload will set the "fired" and "elapsed". */
113};
114
115static const SaveLoad _date_check_desc[] = {
118};
119
124struct DATEChunkHandler : ChunkHandler {
125 DATEChunkHandler() : ChunkHandler("DATE", ChunkType::Table) {}
126
127 void Save() const override
128 {
129 SlTableHeader(_date_desc);
130
131 SlSetArrayIndex(0);
132 SlGlobList(_date_desc);
133 }
134
135 void LoadCommon(const SaveLoadTable &slt, const SaveLoadCompatTable &slct) const
136 {
137 const std::vector<SaveLoad> oslt = SlCompatTableHeader(slt, slct);
138
140 SlGlobList(oslt);
142 }
143
144 void Load() const override
145 {
146 this->LoadCommon(_date_desc, _date_sl_compat);
147 }
148
149
150 void LoadCheck(size_t) const override
151 {
152 this->LoadCommon(_date_check_desc, _date_check_sl_compat);
153
156 }
157 }
158};
159
160static const SaveLoad _view_desc[] = {
166};
167
168struct VIEWChunkHandler : ChunkHandler {
169 VIEWChunkHandler() : ChunkHandler("VIEW", ChunkType::Table) {}
170
171 void Save() const override
172 {
173 SlTableHeader(_view_desc);
174
175 SlSetArrayIndex(0);
176 SlGlobList(_view_desc);
177 }
178
179 void Load() const override
180 {
181 const std::vector<SaveLoad> slt = SlCompatTableHeader(_view_desc, _view_sl_compat);
182
184 SlGlobList(slt);
186 }
187};
188
189static const DATEChunkHandler DATE;
190static const VIEWChunkHandler VIEW;
191static const ChunkHandlerRef misc_chunk_handlers[] = {
192 DATE,
193 VIEW,
194};
195
196extern const ChunkHandlerTable _misc_chunk_handlers(misc_chunk_handlers);
A timeout timer will fire once after the interval.
Definition timer.h:116
static uint16_t sub_date_fract
Subpart of date_fract that we use when calendar days are slower than economy days.
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
static uint days_since_last_month
Number of days that have elapsed since the last month.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
uint _cur_company_tick_index
used to generate a name for one company that doesn't have a name yet per tick
TimeoutTimer< TimerGameTick > _new_competitor_timeout({ TimerGameTick::Priority::CompetitorTimeout, 0 }, []() { if(_game_mode==GameMode::Menu||!AI::CanStartNew()) return;if(_networking &&Company::GetNumItems() >=_settings_client.network.max_companies) return;if(_settings_game.difficulty.competitors_interval==0) return;uint8_t n=0;for(const Company *c :Company::Iterate()) { if(c->is_ai) n++;} if(n >=_settings_game.difficulty.max_no_competitors) return;Command< Commands::CompanyControl >::Post(CompanyCtrlAction::NewAI, CompanyID::Invalid(), CompanyRemoveReason::None, ClientID::Invalid);})
Start a new competitor company if possible.
uint16_t _disaster_delay
Delay counter for considering the next disaster.
Declarations for savegames operations.
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition fios_gui.cpp:42
GameSessionStats _game_session_stats
Statistics about the current session.
Definition gfx.cpp:47
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:46
Functions related to the gfx engine.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
bool DoZoomInOutWindow(ZoomStateChange how, Window *w)
Zooms a viewport in a window in or out.
Definition main_gui.cpp:88
ZoomLevel _saved_scrollpos_zoom
Definition misc_sl.cpp:38
int _saved_scrollpos_x
Definition misc_sl.cpp:36
int _saved_scrollpos_y
Definition misc_sl.cpp:37
uint8_t _age_cargo_skip_counter
Skip aging of cargo? Used before savegame version 162.
Definition misc_sl.cpp:84
uint8_t _trees_tick_ctr
Determines when to consider building more trees.
Definition tree_cmd.cpp:47
Loading for misc chunks before table headers were added.
const SaveLoadCompat _date_check_sl_compat[]
Original field order for _date_check_desc.
const SaveLoadCompat _date_sl_compat[]
Original field order for _date_desc.
const SaveLoadCompat _view_sl_compat[]
Original field order for _view_desc.
Randomizer _random
Random used in the game state calculations.
Pseudo random number generator.
A number of safeguards to prevent using unsafe methods.
std::vector< SaveLoad > SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
Load a table header in a savegame compatible way.
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition saveload.cpp:748
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition saveload.cpp:372
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
void SlGlobList(const SaveLoadTable &slt)
Save or Load (a list of) global variables.
Functions/types related to saving and loading games.
#define SLE_GLOBAL_ADDRESS(variable)
Macro to be able to pass the variable type and construct the SaveLoad::AddressFunction given a global...
Definition saveload.h:760
std::reference_wrapper< const ChunkHandler > ChunkHandlerRef
A reference to ChunkHandler.
Definition saveload.h:512
std::span< const ChunkHandlerRef > ChunkHandlerTable
A table of ChunkHandler entries.
Definition saveload.h:515
std::span< const struct SaveLoadCompat > SaveLoadCompatTable
A table of SaveLoadCompat entries.
Definition saveload.h:518
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition saveload.h:1225
@ BigDates
Saveload version: 31, SVN revision: 5999 Change date from 1920 - 2090 to 0 - 5 000 000.
Definition saveload.h:86
@ TownTolerancePauseMode
Saveload version: 4.0, SVN revision: 1 Town council tolerance and pause mode.
Definition saveload.h:43
@ U64TickCounter
Saveload version: 300, GitHub pull request: 10035 Make tick counter 64bit to avoid wrapping.
Definition saveload.h:345
@ AIStartDate
Saveload version: 309, GitHub pull request: 10653 Removal of individual AI start dates and added a g...
Definition saveload.h:355
@ MultipleRoadStops
Saveload version: 6.0, SVN revision: 1721 Multi tile road stops, and some map size related fixes.
Definition saveload.h:52
@ SavegameId
Saveload version: 313, GitHub pull request: 10719 Add an unique ID to every savegame (used to dedupl...
Definition saveload.h:360
@ NewGRFCustomCargoAging
Saveload version: 162, SVN revision: 22713 NewGRF influence on aging of cargo in vehicles.
Definition saveload.h:243
@ NextCompetitorStartOverflow
Saveload version: 109, SVN revision: 15075 Prevent overflow in the next competitor start counter.
Definition saveload.h:179
@ MinVersion
First savegame version.
Definition saveload.h:36
@ EconomyDate
Saveload version: 326, GitHub pull request: 10700 Split calendar and economy timers and dates.
Definition saveload.h:376
@ IndustryAcceptedHistory
Saveload version: 357, GitHub pull request: 14321 Add per-industry history of cargo delivered and wa...
Definition saveload.h:413
@ CalendarSubDateFract
Saveload version: 328, GitHub pull request: 11428 Add sub_date_fract to measure calendar days.
Definition saveload.h:378
@ RiffToArray
Saveload version: 294, GitHub pull request: 9375 Changed many ChunkType::Riff chunks to ChunkType::A...
Definition saveload.h:337
@ Table
An Array with a header describing the elements.
Definition saveload.h:449
Functions/types related to errors from savegames.
std::span< const struct SaveLoad > SaveLoadTable
A table of SaveLoad entries.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Definition of base types and functions in a cross-platform compatible way.
ChunkHandler(ChunkId id, ChunkType type)
Create this ChunkHandler.
Definition saveload.h:469
Save load date related variables as well as persistent tick counters.
Definition misc_sl.cpp:124
void Save() const override
Save the chunk.
Definition misc_sl.cpp:127
void Load() const override
Load the chunk.
Definition misc_sl.cpp:144
void LoadCheck(size_t) const override
Load the chunk for game preview.
Definition misc_sl.cpp:150
SaveLoad type struct.
Definition saveload.h:763
static SaveLoad Variable(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion, size_t extra=0)
Storage of a variable in some savegame versions.
Definition saveload.h:925
static SaveLoad String(std::string name, AddressFunction< T > address_func, StringValidationSettings string_validation_settings={}, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion, size_t extra=0)
Storage of a string in some savegame versions.
Definition saveload.h:976
void Save() const override
Save the chunk.
Definition misc_sl.cpp:171
void Load() const override
Load the chunk.
Definition misc_sl.cpp:179
Data structure for viewport, display of a part of the world.
int width
Screen width of the viewport.
ZoomLevel zoom
The zoom level of the viewport.
int virtual_width
width << zoom
int height
Screen height of the viewport.
int virtual_height
height << zoom
Data structure for an opened window.
Definition window_gui.h:272
std::unique_ptr< ViewportData > viewport
Pointer to viewport data, if present.
Definition window_gui.h:317
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Functions related to (drawing on) viewports.
@ ZOOM_IN
Zoom in (get more detailed view).
@ ZOOM_NONE
Hack, used to update the button status.
@ ZOOM_OUT
Zoom out (get helicopter view).
Window * GetMainWindow()
Get the main window, i.e.
Definition window.cpp:1228
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1199
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
Functions related to zooming.
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:22
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:20
@ Max
Maximum zoom level.
Definition zoom_type.h:30
@ Min
Minimum zoom level.
Definition zoom_type.h:23
@ End
End for iteration.
Definition zoom_type.h:31