OpenTTD Source 20250312-master-gcdcc6b491d
oldloader.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 <http://www.gnu.org/licenses/>.
6 */
7
10#include "../stdafx.h"
11#include "../debug.h"
12#include "../strings_type.h"
13#include "../string_func.h"
14#include "../settings_type.h"
15#include "../fileio_func.h"
16
17#include "table/strings.h"
18
19#include "saveload_internal.h"
20#include "oldloader.h"
21
22
23#include "../safeguards.h"
24
25static const int TTO_HEADER_SIZE = 41;
26static const int TTD_HEADER_SIZE = 49;
28static const int HEADER_CHECKSUM_SIZE = 2;
29
30uint32_t _bump_assert_value;
31
32static inline OldChunkType GetOldChunkType(OldChunkType type) {return (OldChunkType)GB(type, 0, 4);}
33static inline OldChunkType GetOldChunkVarType(OldChunkType type) {return (OldChunkType)(GB(type, 8, 8) << 8);}
34static inline OldChunkType GetOldChunkFileType(OldChunkType type) {return (OldChunkType)(GB(type, 16, 8) << 16);}
35
41static inline uint8_t CalcOldVarLen(OldChunkType type)
42{
43 switch (GetOldChunkVarType(type)) {
44 case OC_VAR_I8: return sizeof(int8_t);
45 case OC_VAR_U8: return sizeof(uint8_t);
46 case OC_VAR_I16: return sizeof(int16_t);
47 case OC_VAR_U16: return sizeof(uint16_t);
48 case OC_VAR_I32: return sizeof(int32_t);
49 case OC_VAR_U32: return sizeof(uint32_t);
50 case OC_VAR_I64: return sizeof(int64_t);
51 case OC_VAR_U64: return sizeof(uint64_t);
52 default: NOT_REACHED();
53 }
54}
55
62{
63 /* To avoid slow reads, we read BUFFER_SIZE of bytes per time
64 and just return a byte per time */
65 if (ls.buffer_cur >= ls.buffer_count) {
66
67 /* Read some new bytes from the file */
68 int count = static_cast<int>(fread(ls.buffer.data(), 1, ls.buffer.size(), *ls.file));
69
70 /* We tried to read, but there is nothing in the file anymore.. */
71 if (count == 0) {
72 Debug(oldloader, 0, "Read past end of file, loading failed");
73 throw std::exception();
74 }
75
76 ls.buffer_count = count;
77 ls.buffer_cur = 0;
78 }
79
80 return ls.buffer[ls.buffer_cur++];
81}
82
89{
90 /* Old savegames have a nice compression algorithm (RLE)
91 which means that we have a chunk, which starts with a length
92 byte. If that byte is negative, we have to repeat the next byte
93 that many times ( + 1). Else, we need to read that amount of bytes.
94 Works pretty well if you have many zeros behind each other */
95
96 if (ls.chunk_size == 0) {
97 /* Read new chunk */
98 int8_t new_byte = ReadByteFromFile(ls);
99
100 if (new_byte < 0) {
101 /* Repeat next char for new_byte times */
102 ls.decoding = true;
103 ls.decode_char = ReadByteFromFile(ls);
104 ls.chunk_size = -new_byte + 1;
105 } else {
106 ls.decoding = false;
107 ls.chunk_size = new_byte + 1;
108 }
109 }
110
111 ls.total_read++;
112 ls.chunk_size--;
113
114 return ls.decoding ? ls.decode_char : ReadByteFromFile(ls);
115}
116
122bool LoadChunk(LoadgameState &ls, void *base, const OldChunks *chunks)
123{
124 for (const OldChunks *chunk = chunks; chunk->type != OC_END; chunk++) {
125 if (((chunk->type & OC_TTD) && _savegame_type == SGT_TTO) ||
126 ((chunk->type & OC_TTO) && _savegame_type != SGT_TTO)) {
127 /* TTD(P)-only chunk, but TTO savegame || TTO-only chunk, but TTD/TTDP savegame */
128 continue;
129 }
130
131 uint8_t *ptr = (uint8_t*)chunk->ptr;
132
133 for (uint i = 0; i < chunk->amount; i++) {
134 /* Handle simple types */
135 if (GetOldChunkType(chunk->type) != 0) {
136 switch (GetOldChunkType(chunk->type)) {
137 /* Just read the byte and forget about it */
138 case OC_NULL: ReadByte(ls); break;
139
140 case OC_CHUNK:
141 /* Call function, with 'i' as parameter to tell which item we
142 * are going to read */
143 if (!chunk->proc(ls, i)) return false;
144 break;
145
146 case OC_ASSERT:
147 Debug(oldloader, 4, "Assert point: 0x{:X} / 0x{:X}", ls.total_read, reinterpret_cast<size_t>(chunk->ptr) + _bump_assert_value);
148 if (ls.total_read != reinterpret_cast<size_t>(chunk->ptr) + _bump_assert_value) throw std::exception();
149 default: break;
150 }
151 } else {
152 uint64_t res = 0;
153
154 /* Reading from the file: bits 16 to 23 have the FILE type */
155 switch (GetOldChunkFileType(chunk->type)) {
156 case OC_FILE_I8: res = (int8_t)ReadByte(ls); break;
157 case OC_FILE_U8: res = ReadByte(ls); break;
158 case OC_FILE_I16: res = (int16_t)ReadUint16(ls); break;
159 case OC_FILE_U16: res = ReadUint16(ls); break;
160 case OC_FILE_I32: res = (int32_t)ReadUint32(ls); break;
161 case OC_FILE_U32: res = ReadUint32(ls); break;
162 default: NOT_REACHED();
163 }
164
165 /* When both pointers are nullptr, we are just skipping data */
166 if (base == nullptr && chunk->ptr == nullptr) continue;
167
168 /* Chunk refers to a struct member, get address in base. */
169 if (chunk->ptr == nullptr) ptr = (uint8_t *)chunk->offset(base);
170
171 /* Write the data */
172 switch (GetOldChunkVarType(chunk->type)) {
173 case OC_VAR_I8: *(int8_t *)ptr = GB(res, 0, 8); break;
174 case OC_VAR_U8: *(uint8_t *)ptr = GB(res, 0, 8); break;
175 case OC_VAR_I16:*(int16_t *)ptr = GB(res, 0, 16); break;
176 case OC_VAR_U16:*(uint16_t*)ptr = GB(res, 0, 16); break;
177 case OC_VAR_I32:*(int32_t *)ptr = res; break;
178 case OC_VAR_U32:*(uint32_t*)ptr = res; break;
179 case OC_VAR_I64:*(int64_t *)ptr = res; break;
180 case OC_VAR_U64:*(uint64_t*)ptr = res; break;
181 default: NOT_REACHED();
182 }
183
184 /* Increase pointer base for arrays when looping */
185 if (chunk->amount > 1 && chunk->ptr != nullptr) ptr += CalcOldVarLen(chunk->type);
186 }
187 }
188 }
189
190 return true;
191}
192
199static bool VerifyOldNameChecksum(char *title, uint len)
200{
201 uint16_t sum = 0;
202 for (uint i = 0; i < len - HEADER_CHECKSUM_SIZE; i++) {
203 sum += title[i];
204 sum = std::rotl(sum, 1);
205 }
206
207 sum ^= 0xAAAA; // computed checksum
208
209 uint16_t sum2 = title[len - HEADER_CHECKSUM_SIZE]; // checksum in file
210 SB(sum2, 8, 8, title[len - HEADER_CHECKSUM_SIZE + 1]);
211
212 return sum == sum2;
213}
214
215static std::tuple<SavegameType, std::string> DetermineOldSavegameTypeAndName(FileHandle &f)
216{
217 long pos = ftell(f);
218 char buffer[std::max(TTO_HEADER_SIZE, TTD_HEADER_SIZE)];
219 if (pos < 0 || fread(buffer, 1, lengthof(buffer), f) != lengthof(buffer)) {
220 return { SGT_INVALID, "(broken) Unable to read file" };
221 }
222
223 if (VerifyOldNameChecksum(buffer, TTO_HEADER_SIZE) && fseek(f, pos + TTO_HEADER_SIZE, SEEK_SET) == 0) {
224 return { SGT_TTO, "(TTO)" + StrMakeValid({buffer, TTO_HEADER_SIZE - HEADER_CHECKSUM_SIZE}) };
225 }
226
227 if (VerifyOldNameChecksum(buffer, TTD_HEADER_SIZE) && fseek(f, pos + TTD_HEADER_SIZE, SEEK_SET) == 0) {
228 return { SGT_TTD, "(TTD)" + StrMakeValid({buffer, TTD_HEADER_SIZE - HEADER_CHECKSUM_SIZE}) };
229 }
230
231 return { SGT_INVALID, "(broken) Unknown" };
232}
233
234typedef bool LoadOldMainProc(LoadgameState &ls);
235
236bool LoadOldSaveGame(const std::string &file)
237{
238 LoadgameState ls{};
239
240 Debug(oldloader, 3, "Trying to load a TTD(Patch) savegame");
241
242 _bump_assert_value = 0;
243 _settings_game.construction.freeform_edges = false; // disable so we can convert map array (SetTileType is still used)
244
245 /* Open file */
246 ls.file = FioFOpenFile(file, "rb", NO_DIRECTORY);
247
248 if (!ls.file.has_value()) {
249 Debug(oldloader, 0, "Cannot open file '{}'", file);
250 SetSaveLoadError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
251 return false;
252 }
253
254 SavegameType type;
255 std::tie(type, std::ignore) = DetermineOldSavegameTypeAndName(*ls.file);
256
257 LoadOldMainProc *proc = nullptr;
258
259 switch (type) {
260 case SGT_TTO: proc = &LoadTTOMain; break;
261 case SGT_TTD: proc = &LoadTTDMain; break;
262 default:
263 Debug(oldloader, 0, "Unknown savegame type; cannot be loaded");
264 break;
265 }
266
267 _savegame_type = type;
268
269 bool game_loaded;
270 try {
271 game_loaded = proc != nullptr && proc(ls);
272 } catch (...) {
273 game_loaded = false;
274 }
275
276 if (!game_loaded) {
277 SetSaveLoadError(STR_GAME_SAVELOAD_ERROR_DATA_INTEGRITY_CHECK_FAILED);
278 ls.file.reset();
279 return false;
280 }
281
283
284 return true;
285}
286
287std::string GetOldSaveGameName(const std::string &file)
288{
289 auto f = FioFOpenFile(file, "rb", NO_DIRECTORY);
290 if (!f.has_value()) return {};
291
292 std::string name;
293 std::tie(std::ignore, name) = DetermineOldSavegameTypeAndName(*f);
294 return name;
295}
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
std::optional< FileHandle > FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition fileio.cpp:243
@ NO_DIRECTORY
A path without any base directory.
SavegameType _savegame_type
type of savegame we are loading
Definition saveload.cpp:63
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:50
static bool VerifyOldNameChecksum(char *title, uint len)
Verifies the title has a valid checksum.
static const int HEADER_CHECKSUM_SIZE
The size of the checksum in the name/header of the TTD/TTO savegames.
Definition oldloader.cpp:28
static uint8_t CalcOldVarLen(OldChunkType type)
Return expected size in bytes of a OldChunkType.
Definition oldloader.cpp:41
static uint8_t ReadByteFromFile(LoadgameState &ls)
Reads a byte from a file (do not call yourself, use ReadByte())
Definition oldloader.cpp:61
bool LoadChunk(LoadgameState &ls, void *base, const OldChunks *chunks)
Loads a chunk from the old savegame.
uint8_t ReadByte(LoadgameState &ls)
Reads a byte from the buffer and decompress if needed.
Definition oldloader.cpp:88
Declarations of structures and functions used in loader of old savegames.
OldChunkType
Definition oldloader.h:38
@ OC_END
End of the whole chunk, all 32 bits set to zero.
Definition oldloader.h:76
@ OC_TTO
-//- TTO (default is neither of these)
Definition oldloader.h:46
@ OC_TTD
chunk is valid ONLY for TTD savegames
Definition oldloader.h:45
@ SaveLoad
A game paused for saving/loading.
void SetSaveLoadError(StringID str)
Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friend...
SavegameType
Types of save games.
Definition saveload.h:428
@ SGT_TTD
TTD savegame (can be detected incorrectly)
Definition saveload.h:429
@ SGT_INVALID
broken savegame (used internally)
Definition saveload.h:434
@ SGT_TTO
TTO savegame.
Definition saveload.h:433
Declaration of functions used in more save/load files.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:58
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:277
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
Definition string.cpp:125
bool freeform_edges
allow terraforming the tiles at the map edges
ConstructionSettings construction
construction of things in-game
OldChunkType type
Type of field.
Definition oldloader.h:85