Update readme.md
[openttd-joker.git] / src / saveload / saveload.cpp
blobf8efeb322f308ef718f761f10f409d1f29f8792c
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /**
11 * @file saveload.cpp
12 * All actions handling saving and loading goes on in this file. The general actions
13 * are as follows for saving a game (loading is analogous):
14 * <ol>
15 * <li>initialize the writer by creating a temporary memory-buffer for it
16 * <li>go through all to-be saved elements, each 'chunk' (#ChunkHandler) prefixed by a label
17 * <li>use their description array (#SaveLoad) to know what elements to save and in what version
18 * of the game it was active (used when loading)
19 * <li>write all data byte-by-byte to the temporary buffer so it is endian-safe
20 * <li>when the buffer is full; flush it to the output (eg save to file) (_sl.buf, _sl.bufp, _sl.bufe)
21 * <li>repeat this until everything is done, and flush any remaining output to file
22 * </ol>
24 #include "../stdafx.h"
25 #include "../debug.h"
26 #include "../station_base.h"
27 #include "../dock_base.h"
28 #include "../thread/thread.h"
29 #include "../town.h"
30 #include "../network/network.h"
31 #include "../window_func.h"
32 #include "../strings_func.h"
33 #include "../core/endian_func.hpp"
34 #include "../vehicle_base.h"
35 #include "../company_func.h"
36 #include "../date_func.h"
37 #include "../autoreplace_base.h"
38 #include "../roadstop_base.h"
39 #include "../linkgraph/linkgraph.h"
40 #include "../linkgraph/linkgraphjob.h"
41 #include "../statusbar_gui.h"
42 #include "../fileio_func.h"
43 #include "../gamelog.h"
44 #include "../string_func.h"
45 #include "../string_func_extra.h"
46 #include "../fios.h"
47 #include "../error.h"
49 #include "../tbtr_template_vehicle.h"
51 #include "table/strings.h"
53 #include "saveload_internal.h"
54 #include "saveload_filter.h"
56 #include "../safeguards.h"
58 #include <deque>
59 #include <vector>
62 * Previous savegame versions, the trunk revision where they were
63 * introduced and the released version that had that particular
64 * savegame version.
65 * Up to savegame version 18 there is a minor version as well.
67 * 1.0 0.1.x, 0.2.x
68 * 2.0 0.3.0
69 * 2.1 0.3.1, 0.3.2
70 * 3.x lost
71 * 4.0 1
72 * 4.1 122 0.3.3, 0.3.4
73 * 4.2 1222 0.3.5
74 * 4.3 1417
75 * 4.4 1426
76 * 5.0 1429
77 * 5.1 1440
78 * 5.2 1525 0.3.6
79 * 6.0 1721
80 * 6.1 1768
81 * 7.0 1770
82 * 8.0 1786
83 * 9.0 1909
84 * 10.0 2030
85 * 11.0 2033
86 * 11.1 2041
87 * 12.1 2046
88 * 13.1 2080 0.4.0, 0.4.0.1
89 * 14.0 2441
90 * 15.0 2499
91 * 16.0 2817
92 * 16.1 3155
93 * 17.0 3212
94 * 17.1 3218
95 * 18 3227
96 * 19 3396
97 * 20 3403
98 * 21 3472 0.4.x
99 * 22 3726
100 * 23 3915
101 * 24 4150
102 * 25 4259
103 * 26 4466
104 * 27 4757
105 * 28 4987
106 * 29 5070
107 * 30 5946
108 * 31 5999
109 * 32 6001
110 * 33 6440
111 * 34 6455
112 * 35 6602
113 * 36 6624
114 * 37 7182
115 * 38 7195
116 * 39 7269
117 * 40 7326
118 * 41 7348 0.5.x
119 * 42 7573
120 * 43 7642
121 * 44 8144
122 * 45 8501
123 * 46 8705
124 * 47 8735
125 * 48 8935
126 * 49 8969
127 * 50 8973
128 * 51 8978
129 * 52 9066
130 * 53 9316
131 * 54 9613
132 * 55 9638
133 * 56 9667
134 * 57 9691
135 * 58 9762
136 * 59 9779
137 * 60 9874
138 * 61 9892
139 * 62 9905
140 * 63 9956
141 * 64 10006
142 * 65 10210
143 * 66 10211
144 * 67 10236
145 * 68 10266
146 * 69 10319
147 * 70 10541
148 * 71 10567
149 * 72 10601
150 * 73 10903
151 * 74 11030
152 * 75 11107
153 * 76 11139
154 * 77 11172
155 * 78 11176
156 * 79 11188
157 * 80 11228
158 * 81 11244
159 * 82 11410
160 * 83 11589
161 * 84 11822
162 * 85 11874
163 * 86 12042
164 * 87 12129
165 * 88 12134
166 * 89 12160
167 * 90 12293
168 * 91 12347
169 * 92 12381 0.6.x
170 * 93 12648
171 * 94 12816
172 * 95 12924
173 * 96 13226
174 * 97 13256
175 * 98 13375
176 * 99 13838
177 * 100 13952
178 * 101 14233
179 * 102 14332
180 * 103 14598
181 * 104 14735
182 * 105 14803
183 * 106 14919
184 * 107 15027
185 * 108 15045
186 * 109 15075
187 * 110 15148
188 * 111 15190
189 * 112 15290
190 * 113 15340
191 * 114 15601
192 * 115 15695
193 * 116 15893 0.7.x
194 * 117 16037
195 * 118 16129
196 * 119 16242
197 * 120 16439
198 * 121 16694
199 * 122 16855
200 * 123 16909
201 * 124 16993
202 * 125 17113
203 * 126 17433
204 * 127 17439
205 * 128 18281
206 * 129 18292
207 * 130 18404
208 * 131 18481
209 * 132 18522
210 * 133 18674
211 * 134 18703
212 * 135 18719
213 * 136 18764
214 * 137 18912
215 * 138 18942 1.0.x
216 * 139 19346
217 * 140 19382
218 * 141 19799
219 * 142 20003
220 * 143 20048
221 * 144 20334
222 * 145 20376
223 * 146 20446
224 * 147 20621
225 * 148 20659
226 * 149 20832
227 * 150 20857
228 * 151 20918
229 * 152 21171
230 * 153 21263
231 * 154 21426
232 * 155 21453
233 * 156 21728
234 * 157 21862
235 * 158 21933
236 * 159 21962
237 * 160 21974 1.1.x
238 * 161 22567
239 * 162 22713
240 * 163 22767
241 * 164 23290
242 * 165 23304
243 * 166 23415
244 * 167 23504
245 * 168 23637
246 * 169 23816
247 * 170 23826
248 * 171 23835
249 * 172 23947
250 * 173 23967 1.2.0-RC1
251 * 174 23973 1.2.x
252 * 175 24136
253 * 176 24446
254 * 177 24619
255 * 178 24789
256 * 179 24810
257 * 180 24998 1.3.x
258 * 181 25012
259 * 182 25296
260 * 183 25363
261 * 184 25508
262 * 185 25620
263 * 186 25833
264 * 187 25899
265 * 188 26169 1.4.x
266 * 189 26450
267 * 190 26547
268 * 191 26646
269 * 192 26700
270 * 193 26802
271 * 194 26881 1.5.x, 1.6.0
272 * 195 27572 1.6.x
273 * 196 27778 1.7.x
274 * 197 27978 1.8.x
275 * 198
277 * 255 SL_PATCH_PACK
278 * 256 SL_PATCH_PACK_DAYLENGTH
279 * 257 SL_PATCH_PACK_TOWN_BUILDINGS
280 * 258 SL_PATCH_PACK_MAP_FEATURES
281 * 259 SL_PATCH_PACK_SAFE_WAITING_LOCATION
282 * 260 SL_PATCH_PACK_1_2
283 * 261 SL_PATCH_PACK_1_3
284 * 262 SL_PATCH_PACK_1_4
285 * 263 SL_PATCH_PACK_1_5
286 * 264 SL_PATCH_PACK_1_6
287 * 265 SL_PATCH_PACK_1_7
288 * 266 SL_PATCH_PACK_1_8
289 * 267 SL_PATCH_PACK_1_9
290 * 268 SL_PATCH_PACK_1_10
291 * 269 SL_PATCH_PACK_1_11
292 * 270 SL_PATCH_PACK_1_12
293 * 271 SL_PATCH_PACK_1_14
294 * 272 SL_PATCH_PACK_1_15
295 * 273 SL_PATCH_PACK_1_16
296 * 274 SL_PATCH_PACK_1_18
297 * 275 SL_PATCH_PACK_1_18_3
298 * 276 SL_PATCH_PACK_1_18_4
299 * 277 SL_PATCH_PACK_1_18_6
300 * 278 SL_PATCH_PACK_1_19
301 * 279 SL_PATCH_PACK_1_20
302 * 280 SL_PATCH_PACK_1_21
303 * 281 SL_PATCH_PACK_1_22
304 * 282 SL_PATCH_PACK_1_23
305 * 283 SL_PATCH_PACK_1_24
306 * 284 SL_PATCH_PACK_1_25
307 * 285 SL_PATCH_PACK_1_26
308 * 286 SL_PATCH_PACK_1_27
310 extern const uint16 SAVEGAME_VERSION = SL_PATCH_PACK_1_27; ///< Current savegame version of OpenTTD.
312 SavegameType _savegame_type; ///< type of savegame we are loading
313 FileToSaveLoad _file_to_saveload; ///< File to save or load in the openttd loop.
315 uint32 _ttdp_version; ///< version of TTDP savegame (if applicable)
316 uint16 _sl_version; ///< the major savegame version identifier
317 byte _sl_minor_version; ///< the minor savegame version, DO NOT USE!
318 char _savegame_format[8]; ///< how to compress savegames
319 bool _do_autosave; ///< are we doing an autosave at the moment?
321 /** What are we currently doing? */
322 enum SaveLoadAction {
323 SLA_LOAD, ///< loading
324 SLA_SAVE, ///< saving
325 SLA_PTRS, ///< fixing pointers
326 SLA_NULL, ///< null all pointers (on loading error)
327 SLA_LOAD_CHECK, ///< partial loading into #_load_check_data
330 enum NeedLength {
331 NL_NONE = 0, ///< not working in NeedLength mode
332 NL_WANTLENGTH = 1, ///< writing length and data
333 NL_CALCLENGTH = 2, ///< need to calculate the length
336 /** Save in chunks of 128 KiB. */
337 static const size_t MEMORY_CHUNK_SIZE = 128 * 1024;
339 /** A buffer for reading (and buffering) savegame data. */
340 struct ReadBuffer {
341 byte buf[MEMORY_CHUNK_SIZE]; ///< Buffer we're going to read from.
342 byte *bufp; ///< Location we're at reading the buffer.
343 byte *bufe; ///< End of the buffer we can read from.
344 LoadFilter *reader; ///< The filter used to actually read.
345 size_t read; ///< The amount of read bytes so far from the filter.
348 * Initialise our variables.
349 * @param reader The filter to actually read data.
351 ReadBuffer(LoadFilter *reader) : bufp(nullptr), bufe(nullptr), reader(reader), read(0)
355 inline byte ReadByte()
357 if (this->bufp == this->bufe) {
358 size_t len = this->reader->Read(this->buf, lengthof(this->buf));
359 if (len == 0) SlErrorCorrupt("Unexpected end of chunk");
361 this->read += len;
362 this->bufp = this->buf;
363 this->bufe = this->buf + len;
366 return *this->bufp++;
370 * Get the size of the memory dump made so far.
371 * @return The size.
373 size_t GetSize() const
375 return this->read - (this->bufe - this->bufp);
380 /** Container for dumping the savegame (quickly) to memory. */
381 struct MemoryDumper {
382 AutoFreeSmallVector<byte *, 16> blocks; ///< Buffer with blocks of allocated memory.
383 byte *buf; ///< Buffer we're going to write to.
384 byte *bufe; ///< End of the buffer we write to.
386 /** Initialise our variables. */
387 MemoryDumper() : buf(nullptr), bufe(nullptr)
392 * Write a single byte into the dumper.
393 * @param b The byte to write.
395 inline void WriteByte(byte b)
397 /* Are we at the end of this chunk? */
398 if (this->buf == this->bufe) {
399 this->buf = CallocT<byte>(MEMORY_CHUNK_SIZE);
400 *this->blocks.Append() = this->buf;
401 this->bufe = this->buf + MEMORY_CHUNK_SIZE;
404 *this->buf++ = b;
408 * Flush this dumper into a writer.
409 * @param writer The filter we want to use.
411 void Flush(SaveFilter *writer)
413 uint i = 0;
414 size_t t = this->GetSize();
416 while (t > 0) {
417 size_t to_write = min(MEMORY_CHUNK_SIZE, t);
419 writer->Write(this->blocks[i++], to_write);
420 t -= to_write;
423 writer->Finish();
427 * Get the size of the memory dump made so far.
428 * @return The size.
430 size_t GetSize() const
432 return this->blocks.Length() * MEMORY_CHUNK_SIZE - (this->bufe - this->buf);
436 /** The saveload struct, containing reader-writer functions, buffer, version, etc. */
437 struct SaveLoadParams {
438 SaveLoadAction action; ///< are we doing a save or a load atm.
439 NeedLength need_length; ///< working in NeedLength (Autolength) mode?
440 byte block_mode; ///< ???
441 bool error; ///< did an error occur or not
443 size_t obj_len; ///< the length of the current object we are busy with
444 int array_index, last_array_index; ///< in the case of an array, the current and last positions
446 MemoryDumper *dumper; ///< Memory dumper to write the savegame to.
447 SaveFilter *sf; ///< Filter to write the savegame to.
449 ReadBuffer *reader; ///< Savegame reading buffer.
450 LoadFilter *lf; ///< Filter to read the savegame from.
452 StringID error_str; ///< the translatable error message to show
453 char *extra_msg; ///< the error message
455 byte ff_state; ///< The state of fast-forward when saving started.
456 bool saveinprogress; ///< Whether there is currently a save in progress.
459 static SaveLoadParams _sl; ///< Parameters used for/at saveload.
461 /* these define the chunks */
462 extern const ChunkHandler _gamelog_chunk_handlers[];
463 extern const ChunkHandler _map_chunk_handlers[];
464 extern const ChunkHandler _misc_chunk_handlers[];
465 extern const ChunkHandler _name_chunk_handlers[];
466 extern const ChunkHandler _cheat_chunk_handlers[] ;
467 extern const ChunkHandler _setting_chunk_handlers[];
468 extern const ChunkHandler _company_chunk_handlers[];
469 extern const ChunkHandler _engine_chunk_handlers[];
470 extern const ChunkHandler _veh_chunk_handlers[];
471 extern const ChunkHandler _waypoint_chunk_handlers[];
472 extern const ChunkHandler _depot_chunk_handlers[];
473 extern const ChunkHandler _order_chunk_handlers[];
474 extern const ChunkHandler _town_chunk_handlers[];
475 extern const ChunkHandler _sign_chunk_handlers[];
476 extern const ChunkHandler _station_chunk_handlers[];
477 extern const ChunkHandler _industry_chunk_handlers[];
478 extern const ChunkHandler _economy_chunk_handlers[];
479 extern const ChunkHandler _subsidy_chunk_handlers[];
480 extern const ChunkHandler _cargomonitor_chunk_handlers[];
481 extern const ChunkHandler _goal_chunk_handlers[];
482 extern const ChunkHandler _story_page_chunk_handlers[];
483 extern const ChunkHandler _ai_chunk_handlers[];
484 extern const ChunkHandler _game_chunk_handlers[];
485 extern const ChunkHandler _animated_tile_chunk_handlers[];
486 extern const ChunkHandler _newgrf_chunk_handlers[];
487 extern const ChunkHandler _group_chunk_handlers[];
488 extern const ChunkHandler _cargopacket_chunk_handlers[];
489 extern const ChunkHandler _autoreplace_chunk_handlers[];
490 extern const ChunkHandler _labelmaps_chunk_handlers[];
491 extern const ChunkHandler _linkgraph_chunk_handlers[];
492 extern const ChunkHandler _airport_chunk_handlers[];
493 extern const ChunkHandler _object_chunk_handlers[];
494 extern const ChunkHandler _persistent_storage_chunk_handlers[];
495 extern const ChunkHandler _plan_chunk_handlers[];
496 extern const ChunkHandler _trace_restrict_chunk_handlers[];
497 extern const ChunkHandler _template_replacement_chunk_handlers[];
498 extern const ChunkHandler _template_vehicle_chunk_handlers[];
499 extern const ChunkHandler _logic_signal_handlers[];
500 extern const ChunkHandler _bridge_signal_chunk_handlers[];
501 extern const ChunkHandler _tunnel_chunk_handlers[];
503 /** Array of all chunks in a savegame, \c nullptr terminated. */
504 static const ChunkHandler * const _chunk_handlers[] = {
505 _gamelog_chunk_handlers,
506 _map_chunk_handlers,
507 _misc_chunk_handlers,
508 _name_chunk_handlers,
509 _cheat_chunk_handlers,
510 _setting_chunk_handlers,
511 _veh_chunk_handlers,
512 _waypoint_chunk_handlers,
513 _depot_chunk_handlers,
514 _order_chunk_handlers,
515 _industry_chunk_handlers,
516 _economy_chunk_handlers,
517 _subsidy_chunk_handlers,
518 _cargomonitor_chunk_handlers,
519 _goal_chunk_handlers,
520 _story_page_chunk_handlers,
521 _engine_chunk_handlers,
522 _town_chunk_handlers,
523 _sign_chunk_handlers,
524 _station_chunk_handlers,
525 _company_chunk_handlers,
526 _ai_chunk_handlers,
527 _game_chunk_handlers,
528 _animated_tile_chunk_handlers,
529 _newgrf_chunk_handlers,
530 _group_chunk_handlers,
531 _cargopacket_chunk_handlers,
532 _autoreplace_chunk_handlers,
533 _labelmaps_chunk_handlers,
534 _linkgraph_chunk_handlers,
535 _airport_chunk_handlers,
536 _object_chunk_handlers,
537 _persistent_storage_chunk_handlers,
538 _plan_chunk_handlers,
539 _trace_restrict_chunk_handlers,
540 _template_replacement_chunk_handlers,
541 _template_vehicle_chunk_handlers,
542 _logic_signal_handlers,
543 _bridge_signal_chunk_handlers,
544 _tunnel_chunk_handlers,
545 nullptr,
549 * Iterate over all chunk handlers.
550 * @param ch the chunk handler iterator
552 #define FOR_ALL_CHUNK_HANDLERS(ch) \
553 for (const ChunkHandler * const *chsc = _chunk_handlers; *chsc != nullptr; chsc++) \
554 for (const ChunkHandler *ch = *chsc; ch != nullptr; ch = (ch->flags & CH_LAST) ? nullptr : ch + 1)
556 /** Null all pointers (convert index -> nullptr) */
557 static void SlNullPointers()
559 _sl.action = SLA_NULL;
561 /* We don't want any savegame conversion code to run
562 * during NULLing; especially those that try to get
563 * pointers from other pools. */
564 _sl_version = SAVEGAME_VERSION;
566 DEBUG(sl, 1, "Nulling pointers");
568 FOR_ALL_CHUNK_HANDLERS(ch) {
569 if (ch->ptrs_proc != nullptr) {
570 DEBUG(sl, 2, "Nulling pointers for %c%c%c%c", ch->id >> 24, ch->id >> 16, ch->id >> 8, ch->id);
571 ch->ptrs_proc();
575 DEBUG(sl, 1, "All pointers nulled");
577 assert(_sl.action == SLA_NULL);
581 * Error handler. Sets everything up to show an error message and to clean
582 * up the mess of a partial savegame load.
583 * @param string The translatable error message to show.
584 * @param extra_msg An extra error message coming from one of the APIs.
585 * @note This function does never return as it throws an exception to
586 * break out of all the saveload code.
588 void NORETURN SlError(StringID string, const char *extra_msg)
590 /* Distinguish between loading into _load_check_data vs. normal save/load. */
591 if (_sl.action == SLA_LOAD_CHECK) {
592 _load_check_data.error = string;
593 free(_load_check_data.error_data);
594 _load_check_data.error_data = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
595 } else {
596 _sl.error_str = string;
597 free(_sl.extra_msg);
598 _sl.extra_msg = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
601 /* We have to nullptr all pointers here; we might be in a state where
602 * the pointers are actually filled with indices, which means that
603 * when we access them during cleaning the pool dereferences of
604 * those indices will be made with segmentation faults as result. */
605 if (_sl.action == SLA_LOAD || _sl.action == SLA_PTRS) SlNullPointers();
606 throw std::exception();
610 * Error handler for corrupt savegames. Sets everything up to show the
611 * error message and to clean up the mess of a partial savegame load.
612 * @param msg Location the corruption has been spotted.
613 * @note This function does never return as it throws an exception to
614 * break out of all the saveload code.
616 void NORETURN SlErrorCorrupt(const char *msg)
618 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, msg);
622 typedef void (*AsyncSaveFinishProc)(); ///< Callback for when the savegame loading is finished.
623 static AsyncSaveFinishProc _async_save_finish = nullptr; ///< Callback to call when the savegame loading is finished.
624 static ThreadObject *_save_thread; ///< The thread we're using to compress and write a savegame
627 * Called by save thread to tell we finished saving.
628 * @param proc The callback to call when saving is done.
630 static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
632 if (_exit_game) return;
633 while (_async_save_finish != nullptr) CSleep(10);
635 _async_save_finish = proc;
639 * Handle async save finishes.
641 void ProcessAsyncSaveFinish()
643 if (_async_save_finish == nullptr) return;
645 _async_save_finish();
647 _async_save_finish = nullptr;
649 if (_save_thread != nullptr) {
650 _save_thread->Join();
651 delete _save_thread;
652 _save_thread = nullptr;
657 * Wrapper for reading a byte from the buffer.
658 * @return The read byte.
660 byte SlReadByte()
662 return _sl.reader->ReadByte();
666 * Wrapper for writing a byte to the dumper.
667 * @param b The byte to write.
669 void SlWriteByte(byte b)
671 _sl.dumper->WriteByte(b);
674 static inline int SlReadUint16()
676 int x = SlReadByte() << 8;
677 return x | SlReadByte();
680 static inline uint32 SlReadUint32()
682 uint32 x = SlReadUint16() << 16;
683 return x | SlReadUint16();
686 static inline uint64 SlReadUint64()
688 uint32 x = SlReadUint32();
689 uint32 y = SlReadUint32();
690 return (uint64)x << 32 | y;
693 static inline void SlWriteUint16(uint16 v)
695 SlWriteByte(GB(v, 8, 8));
696 SlWriteByte(GB(v, 0, 8));
699 static inline void SlWriteUint32(uint32 v)
701 SlWriteUint16(GB(v, 16, 16));
702 SlWriteUint16(GB(v, 0, 16));
705 static inline void SlWriteUint64(uint64 x)
707 SlWriteUint32((uint32)(x >> 32));
708 SlWriteUint32((uint32)x);
712 * Read in bytes from the file/data structure but don't do
713 * anything with them, discarding them in effect
714 * @param length The amount of bytes that is being treated this way
716 static inline void SlSkipBytes(size_t length)
718 for (; length != 0; length--) SlReadByte();
722 * Read in the header descriptor of an object or an array.
723 * If the highest bit is set (7), then the index is bigger than 127
724 * elements, so use the next byte to read in the real value.
725 * The actual value is then both bytes added with the first shifted
726 * 8 bits to the left, and dropping the highest bit (which only indicated a big index).
727 * x = ((x & 0x7F) << 8) + SlReadByte();
728 * @return Return the value of the index
730 static uint SlReadSimpleGamma()
732 uint i = SlReadByte();
733 if (HasBit(i, 7)) {
734 i &= ~0x80;
735 if (HasBit(i, 6)) {
736 i &= ~0x40;
737 if (HasBit(i, 5)) {
738 i &= ~0x20;
739 if (HasBit(i, 4)) {
740 i &= ~0x10;
741 if (HasBit(i, 3)) {
742 SlErrorCorrupt("Unsupported gamma");
744 i = SlReadByte(); // 32 bits only.
746 i = (i << 8) | SlReadByte();
748 i = (i << 8) | SlReadByte();
750 i = (i << 8) | SlReadByte();
752 return i;
756 * Write the header descriptor of an object or an array.
757 * If the element is bigger than 127, use 2 bytes for saving
758 * and use the highest byte of the first written one as a notice
759 * that the length consists of 2 bytes, etc.. like this:
760 * 0xxxxxxx
761 * 10xxxxxx xxxxxxxx
762 * 110xxxxx xxxxxxxx xxxxxxxx
763 * 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
764 * 11110--- xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
765 * We could extend the scheme ad infinum to support arbitrarily
766 * large chunks, but as sizeof(size_t) == 4 is still very common
767 * we don't support anything above 32 bits. That's why in the last
768 * case the 3 most significant bits are unused.
769 * @param i Index being written
772 static void SlWriteSimpleGamma(size_t i)
774 if (i >= (1 << 7)) {
775 if (i >= (1 << 14)) {
776 if (i >= (1 << 21)) {
777 if (i >= (1 << 28)) {
778 assert(i <= UINT32_MAX); // We can only support 32 bits for now.
779 SlWriteByte((byte)(0xF0));
780 SlWriteByte((byte)(i >> 24));
781 } else {
782 SlWriteByte((byte)(0xE0 | (i >> 24)));
784 SlWriteByte((byte)(i >> 16));
785 } else {
786 SlWriteByte((byte)(0xC0 | (i >> 16)));
788 SlWriteByte((byte)(i >> 8));
789 } else {
790 SlWriteByte((byte)(0x80 | (i >> 8)));
793 SlWriteByte((byte)i);
796 /** Return how many bytes used to encode a gamma value */
797 static inline uint SlGetGammaLength(size_t i)
799 return 1 + (i >= (1 << 7)) + (i >= (1 << 14)) + (i >= (1 << 21)) + (i >= (1 << 28));
802 static inline uint SlReadSparseIndex()
804 return SlReadSimpleGamma();
807 static inline void SlWriteSparseIndex(uint index)
809 SlWriteSimpleGamma(index);
812 static inline uint SlReadArrayLength()
814 return SlReadSimpleGamma();
817 static inline void SlWriteArrayLength(size_t length)
819 SlWriteSimpleGamma(length);
822 static inline uint SlGetArrayLength(size_t length)
824 return SlGetGammaLength(length);
828 * Return the size in bytes of a certain type of normal/atomic variable
829 * as it appears in memory. See VarTypes
830 * @param conv VarType type of variable that is used for calculating the size
831 * @return Return the size of this type in bytes
833 static inline uint SlCalcConvMemLen(VarType conv)
835 static const byte conv_mem_size[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
836 byte length = GB(conv, 4, 4);
838 switch (length << 4) {
839 case SLE_VAR_STRB:
840 case SLE_VAR_STRBQ:
841 case SLE_VAR_STR:
842 case SLE_VAR_STRQ:
843 return SlReadArrayLength();
845 default:
846 assert(length < lengthof(conv_mem_size));
847 return conv_mem_size[length];
852 * Return the size in bytes of a certain type of normal/atomic variable
853 * as it appears in a saved game. See VarTypes
854 * @param conv VarType type of variable that is used for calculating the size
855 * @return Return the size of this type in bytes
857 static inline byte SlCalcConvFileLen(VarType conv)
859 static const byte conv_file_size[] = {1, 1, 2, 2, 4, 4, 8, 8, 2};
860 byte length = GB(conv, 0, 4);
861 assert(length < lengthof(conv_file_size));
862 return conv_file_size[length];
865 /** Return the size in bytes of a reference (pointer) */
866 static inline size_t SlCalcRefLen()
868 return IsSavegameVersionBefore(69) ? 2 : 4;
871 void SlSetArrayIndex(uint index)
873 _sl.need_length = NL_WANTLENGTH;
874 _sl.array_index = index;
877 static size_t _next_offs;
880 * Iterate through the elements of an array and read the whole thing
881 * @return The index of the object, or -1 if we have reached the end of current block
883 int SlIterateArray()
885 int index;
887 /* After reading in the whole array inside the loop
888 * we must have read in all the data, so we must be at end of current block. */
889 if (_next_offs != 0 && _sl.reader->GetSize() != _next_offs) SlErrorCorrupt("Invalid chunk size");
891 for (;;) {
892 uint length = SlReadArrayLength();
893 if (length == 0) {
894 _next_offs = 0;
895 return -1;
898 _sl.obj_len = --length;
899 _next_offs = _sl.reader->GetSize() + length;
901 switch (_sl.block_mode) {
902 case CH_SPARSE_ARRAY: index = (int)SlReadSparseIndex(); break;
903 case CH_ARRAY: index = _sl.array_index++; break;
904 default:
905 DEBUG(sl, 0, "SlIterateArray error");
906 return -1; // error
909 if (length != 0) return index;
914 * Skip an array or sparse array
916 void SlSkipArray()
918 while (SlIterateArray() != -1) {
919 SlSkipBytes(_next_offs - _sl.reader->GetSize());
924 * Sets the length of either a RIFF object or the number of items in an array.
925 * This lets us load an object or an array of arbitrary size
926 * @param length The length of the sought object/array
928 void SlSetLength(size_t length)
930 assert(_sl.action == SLA_SAVE);
932 switch (_sl.need_length) {
933 case NL_WANTLENGTH:
934 _sl.need_length = NL_NONE;
935 switch (_sl.block_mode) {
936 case CH_RIFF:
937 /* Ugly encoding of >16M RIFF chunks
938 * The lower 24 bits are normal
939 * The uppermost 4 bits are bits 24:27 */
940 assert(length < (1 << 28));
941 SlWriteUint32((uint32)((length & 0xFFFFFF) | ((length >> 24) << 28)));
942 break;
943 case CH_ARRAY:
944 assert(_sl.last_array_index <= _sl.array_index);
945 while (++_sl.last_array_index <= _sl.array_index) {
946 SlWriteArrayLength(1);
948 SlWriteArrayLength(length + 1);
949 break;
950 case CH_SPARSE_ARRAY:
951 SlWriteArrayLength(length + 1 + SlGetArrayLength(_sl.array_index)); // Also include length of sparse index.
952 SlWriteSparseIndex(_sl.array_index);
953 break;
954 default: NOT_REACHED();
956 break;
958 case NL_CALCLENGTH:
959 _sl.obj_len += (int)length;
960 break;
962 default: NOT_REACHED();
967 * Save/Load bytes. These do not need to be converted to Little/Big Endian
968 * so directly write them or read them to/from file
969 * @param ptr The source or destination of the object being manipulated
970 * @param length number of bytes this fast CopyBytes lasts
972 static void SlCopyBytes(void *ptr, size_t length)
974 byte *p = (byte *)ptr;
976 switch (_sl.action) {
977 case SLA_LOAD_CHECK:
978 case SLA_LOAD:
979 for (; length != 0; length--) *p++ = SlReadByte();
980 break;
981 case SLA_SAVE:
982 for (; length != 0; length--) SlWriteByte(*p++);
983 break;
984 default: NOT_REACHED();
988 /** Get the length of the current object */
989 size_t SlGetFieldLength()
991 return _sl.obj_len;
995 * Return a signed-long version of the value of a setting
996 * @param ptr pointer to the variable
997 * @param conv type of variable, can be a non-clean
998 * type, eg one with other flags because it is parsed
999 * @return returns the value of the pointer-setting
1001 int64 ReadValue(const void *ptr, VarType conv)
1003 switch (GetVarMemType(conv)) {
1004 case SLE_VAR_BL: return (*(const bool *)ptr != 0);
1005 case SLE_VAR_I8: return *(const int8 *)ptr;
1006 case SLE_VAR_U8: return *(const byte *)ptr;
1007 case SLE_VAR_I16: return *(const int16 *)ptr;
1008 case SLE_VAR_U16: return *(const uint16*)ptr;
1009 case SLE_VAR_I32: return *(const int32 *)ptr;
1010 case SLE_VAR_U32: return *(const uint32*)ptr;
1011 case SLE_VAR_I64: return *(const int64 *)ptr;
1012 case SLE_VAR_U64: return *(const uint64*)ptr;
1013 case SLE_VAR_NULL:return 0;
1014 default: NOT_REACHED();
1019 * Write the value of a setting
1020 * @param ptr pointer to the variable
1021 * @param conv type of variable, can be a non-clean type, eg
1022 * with other flags. It is parsed upon read
1023 * @param val the new value being given to the variable
1025 void WriteValue(void *ptr, VarType conv, int64 val)
1027 switch (GetVarMemType(conv)) {
1028 case SLE_VAR_BL: *(bool *)ptr = (val != 0); break;
1029 case SLE_VAR_I8: *(int8 *)ptr = val; break;
1030 case SLE_VAR_U8: *(byte *)ptr = val; break;
1031 case SLE_VAR_I16: *(int16 *)ptr = val; break;
1032 case SLE_VAR_U16: *(uint16*)ptr = val; break;
1033 case SLE_VAR_I32: *(int32 *)ptr = val; break;
1034 case SLE_VAR_U32: *(uint32*)ptr = val; break;
1035 case SLE_VAR_I64: *(int64 *)ptr = val; break;
1036 case SLE_VAR_U64: *(uint64*)ptr = val; break;
1037 case SLE_VAR_NAME: *(char**)ptr = CopyFromOldName(val); break;
1038 case SLE_VAR_NULL: break;
1039 default: NOT_REACHED();
1044 * Handle all conversion and typechecking of variables here.
1045 * In the case of saving, read in the actual value from the struct
1046 * and then write them to file, endian safely. Loading a value
1047 * goes exactly the opposite way
1048 * @param ptr The object being filled/read
1049 * @param conv VarType type of the current element of the struct
1051 static void SlSaveLoadConv(void *ptr, VarType conv)
1053 switch (_sl.action) {
1054 case SLA_SAVE: {
1055 int64 x = ReadValue(ptr, conv);
1057 /* Write the value to the file and check if its value is in the desired range */
1058 switch (GetVarFileType(conv)) {
1059 case SLE_FILE_I8: assert(x >= -128 && x <= 127); SlWriteByte(x);break;
1060 case SLE_FILE_U8: assert(x >= 0 && x <= 255); SlWriteByte(x);break;
1061 case SLE_FILE_I16:assert(x >= -32768 && x <= 32767); SlWriteUint16(x);break;
1062 case SLE_FILE_STRINGID:
1063 case SLE_FILE_U16:assert(x >= 0 && x <= 65535); SlWriteUint16(x);break;
1064 case SLE_FILE_I32:
1065 case SLE_FILE_U32: SlWriteUint32((uint32)x);break;
1066 case SLE_FILE_I64:
1067 case SLE_FILE_U64: SlWriteUint64(x);break;
1068 default: NOT_REACHED();
1070 break;
1072 case SLA_LOAD_CHECK:
1073 case SLA_LOAD: {
1074 int64 x;
1075 /* Read a value from the file */
1076 switch (GetVarFileType(conv)) {
1077 case SLE_FILE_I8: x = (int8 )SlReadByte(); break;
1078 case SLE_FILE_U8: x = (byte )SlReadByte(); break;
1079 case SLE_FILE_I16: x = (int16 )SlReadUint16(); break;
1080 case SLE_FILE_U16: x = (uint16)SlReadUint16(); break;
1081 case SLE_FILE_I32: x = (int32 )SlReadUint32(); break;
1082 case SLE_FILE_U32: x = (uint32)SlReadUint32(); break;
1083 case SLE_FILE_I64: x = (int64 )SlReadUint64(); break;
1084 case SLE_FILE_U64: x = (uint64)SlReadUint64(); break;
1085 case SLE_FILE_STRINGID: x = RemapOldStringID((uint16)SlReadUint16()); break;
1086 default: NOT_REACHED();
1089 /* Write The value to the struct. These ARE endian safe. */
1090 WriteValue(ptr, conv, x);
1091 break;
1093 case SLA_PTRS: break;
1094 case SLA_NULL: break;
1095 default: NOT_REACHED();
1100 * Calculate the net length of a string. This is in almost all cases
1101 * just strlen(), but if the string is not properly terminated, we'll
1102 * resort to the maximum length of the buffer.
1103 * @param ptr pointer to the stringbuffer
1104 * @param length maximum length of the string (buffer). If -1 we don't care
1105 * about a maximum length, but take string length as it is.
1106 * @return return the net length of the string
1108 static inline size_t SlCalcNetStringLen(const char *ptr, size_t length)
1110 if (ptr == nullptr) return 0;
1111 return min(strlen(ptr), length - 1);
1115 * Calculate the gross length of the std::string that it
1116 * will occupy in the savegame. This includes the real length,
1117 * and the length that the index will occupy.
1118 * @param str reference to the std::string
1119 * @return return the gross length of the string
1121 static inline size_t SlCalcStdStrLen(const std::string &str)
1123 return str.size() + SlGetArrayLength(str.size()); // also include the length of the index
1127 * Calculate the gross length of the string that it
1128 * will occupy in the savegame. This includes the real length, returned
1129 * by SlCalcNetStringLen and the length that the index will occupy.
1130 * @param ptr pointer to the stringbuffer
1131 * @param length maximum length of the string (buffer size, etc.)
1132 * @param conv type of data been used
1133 * @return return the gross length of the string
1135 static inline size_t SlCalcStringLen(const void *ptr, size_t length, VarType conv)
1137 size_t len;
1138 const char *str;
1140 switch (GetVarMemType(conv)) {
1141 default: NOT_REACHED();
1142 case SLE_VAR_STR:
1143 case SLE_VAR_STRQ:
1144 str = *(const char * const *)ptr;
1145 len = SIZE_MAX;
1146 break;
1147 case SLE_VAR_STRB:
1148 case SLE_VAR_STRBQ:
1149 str = (const char *)ptr;
1150 len = length;
1151 break;
1154 len = SlCalcNetStringLen(str, len);
1155 return len + SlGetArrayLength(len); // also include the length of the index
1159 * Save/Load a string.
1160 * @param ptr the string being manipulated
1161 * @param length of the string (full length)
1162 * @param conv must be SLE_FILE_STRING
1164 static void SlString(void *ptr, size_t length, VarType conv)
1166 switch (_sl.action) {
1167 case SLA_SAVE: {
1168 size_t len;
1169 switch (GetVarMemType(conv)) {
1170 default: NOT_REACHED();
1171 case SLE_VAR_STRB:
1172 case SLE_VAR_STRBQ:
1173 len = SlCalcNetStringLen((char *)ptr, length);
1174 break;
1175 case SLE_VAR_STR:
1176 case SLE_VAR_STRQ:
1177 ptr = *(char **)ptr;
1178 len = SlCalcNetStringLen((char *)ptr, SIZE_MAX);
1179 break;
1182 SlWriteArrayLength(len);
1183 SlCopyBytes(ptr, len);
1184 break;
1186 case SLA_LOAD_CHECK:
1187 case SLA_LOAD: {
1188 size_t len = SlReadArrayLength();
1190 switch (GetVarMemType(conv)) {
1191 default: NOT_REACHED();
1192 case SLE_VAR_STRB:
1193 case SLE_VAR_STRBQ:
1194 if (len >= length) {
1195 DEBUG(sl, 1, "String length in savegame is bigger than buffer, truncating");
1196 SlCopyBytes(ptr, length);
1197 SlSkipBytes(len - length);
1198 len = length - 1;
1199 } else {
1200 SlCopyBytes(ptr, len);
1202 break;
1203 case SLE_VAR_STR:
1204 case SLE_VAR_STRQ: // Malloc'd string, free previous incarnation, and allocate
1205 free(*(char **)ptr);
1206 if (len == 0) {
1207 *(char **)ptr = nullptr;
1208 return;
1209 } else {
1210 *(char **)ptr = MallocT<char>(len + 1); // terminating '\0'
1211 ptr = *(char **)ptr;
1212 SlCopyBytes(ptr, len);
1214 break;
1217 ((char *)ptr)[len] = '\0'; // properly terminate the string
1218 StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK;
1219 if ((conv & SLF_ALLOW_CONTROL) != 0) {
1220 settings = settings | SVS_ALLOW_CONTROL_CODE;
1221 if (IsSavegameVersionBefore(169)) {
1222 str_fix_scc_encoded((char *)ptr, (char *)ptr + len);
1225 if ((conv & SLF_ALLOW_NEWLINE) != 0) {
1226 settings = settings | SVS_ALLOW_NEWLINE;
1228 str_validate((char *)ptr, (char *)ptr + len, settings);
1229 break;
1231 case SLA_PTRS: break;
1232 case SLA_NULL: break;
1233 default: NOT_REACHED();
1238 * Save/Load a std::string.
1239 * @param ptr the std::string being manipulated
1240 * @param conv must be SLE_FILE_STRING
1242 static void SlStdString(std::string &str, VarType conv)
1244 switch (_sl.action) {
1245 case SLA_SAVE: {
1246 SlWriteArrayLength(str.size());
1247 SlCopyBytes(const_cast<char *>(str.data()), str.size());
1248 break;
1250 case SLA_LOAD_CHECK:
1251 case SLA_LOAD: {
1252 size_t len = SlReadArrayLength();
1253 str.resize(len);
1254 SlCopyBytes(const_cast<char *>(str.c_str()), len);
1256 StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK;
1257 if ((conv & SLF_ALLOW_CONTROL) != 0) {
1258 settings = settings | SVS_ALLOW_CONTROL_CODE;
1260 if ((conv & SLF_ALLOW_NEWLINE) != 0) {
1261 settings = settings | SVS_ALLOW_NEWLINE;
1263 str_validate(str, settings);
1264 break;
1266 case SLA_PTRS: break;
1267 case SLA_NULL: break;
1268 default: NOT_REACHED();
1273 * Return the size in bytes of a certain type of atomic array
1274 * @param length The length of the array counted in elements
1275 * @param conv VarType type of the variable that is used in calculating the size
1277 static inline size_t SlCalcArrayLen(size_t length, VarType conv)
1279 return SlCalcConvFileLen(conv) * length;
1283 * Save/Load an array.
1284 * @param array The array being manipulated
1285 * @param length The length of the array in elements
1286 * @param conv VarType type of the atomic array (int, byte, uint64, etc.)
1288 void SlArray(void *array, size_t length, VarType conv)
1290 if (_sl.action == SLA_PTRS || _sl.action == SLA_NULL) return;
1292 /* Automatically calculate the length? */
1293 if (_sl.need_length != NL_NONE) {
1294 SlSetLength(SlCalcArrayLen(length, conv));
1295 /* Determine length only? */
1296 if (_sl.need_length == NL_CALCLENGTH) return;
1299 /* NOTICE - handle some buggy stuff, in really old versions everything was saved
1300 * as a byte-type. So detect this, and adjust array size accordingly */
1301 if (_sl.action != SLA_SAVE && _sl_version == 0) {
1302 /* all arrays except difficulty settings */
1303 if (conv == SLE_INT16 || conv == SLE_UINT16 || conv == SLE_STRINGID ||
1304 conv == SLE_INT32 || conv == SLE_UINT32) {
1305 SlCopyBytes(array, length * SlCalcConvFileLen(conv));
1306 return;
1308 /* used for conversion of Money 32bit->64bit */
1309 if (conv == (SLE_FILE_I32 | SLE_VAR_I64)) {
1310 for (uint i = 0; i < length; i++) {
1311 ((int64*)array)[i] = (int32)BSWAP32(SlReadUint32());
1313 return;
1317 /* If the size of elements is 1 byte both in file and memory, no special
1318 * conversion is needed, use specialized copy-copy function to speed up things */
1319 if (conv == SLE_INT8 || conv == SLE_UINT8) {
1320 SlCopyBytes(array, length);
1321 } else {
1322 byte *a = (byte*)array;
1323 byte mem_size = SlCalcConvMemLen(conv);
1325 for (; length != 0; length --) {
1326 SlSaveLoadConv(a, conv);
1327 a += mem_size; // get size
1334 * Pointers cannot be saved to a savegame, so this functions gets
1335 * the index of the item, and if not available, it hussles with
1336 * pointers (looks really bad :()
1337 * Remember that a nullptr item has value 0, and all
1338 * indices have +1, so vehicle 0 is saved as index 1.
1339 * @param obj The object that we want to get the index of
1340 * @param rt SLRefType type of the object the index is being sought of
1341 * @return Return the pointer converted to an index of the type pointed to
1343 static size_t ReferenceToInt(const void *obj, SLRefType rt)
1345 assert(_sl.action == SLA_SAVE);
1347 if (obj == nullptr) return 0;
1349 switch (rt) {
1350 case REF_VEHICLE_OLD: // Old vehicles we save as new ones
1351 case REF_VEHICLE: return ((const Vehicle*)obj)->index + 1;
1352 case REF_TEMPLATE_VEHICLE: return ((const TemplateVehicle*)obj)->index + 1;
1353 case REF_STATION: return ((const Station*)obj)->index + 1;
1354 case REF_TOWN: return ((const Town*)obj)->index + 1;
1355 case REF_ORDER: return ((const Order*)obj)->index + 1;
1356 case REF_ROADSTOPS: return ((const RoadStop*)obj)->index + 1;
1357 case REF_ENGINE_RENEWS: return ((const EngineRenew*)obj)->index + 1;
1358 case REF_CARGO_PACKET: return ((const CargoPacket*)obj)->index + 1;
1359 case REF_ORDERLIST: return ((const OrderList*)obj)->index + 1;
1360 case REF_STORAGE: return ((const PersistentStorage*)obj)->index + 1;
1361 case REF_LINK_GRAPH: return ((const LinkGraph*)obj)->index + 1;
1362 case REF_LINK_GRAPH_JOB: return ((const LinkGraphJob*)obj)->index + 1;
1363 case REF_DOCKS: return ((const Dock*)obj)->index + 1;
1364 default: NOT_REACHED();
1369 * Pointers cannot be loaded from a savegame, so this function
1370 * gets the index from the savegame and returns the appropriate
1371 * pointer from the already loaded base.
1372 * Remember that an index of 0 is a nullptr pointer so all indices
1373 * are +1 so vehicle 0 is saved as 1.
1374 * @param index The index that is being converted to a pointer
1375 * @param rt SLRefType type of the object the pointer is sought of
1376 * @return Return the index converted to a pointer of any type
1378 static void *IntToReference(size_t index, SLRefType rt)
1380 assert_compile(sizeof(size_t) <= sizeof(void *));
1382 assert(_sl.action == SLA_PTRS);
1384 /* After version 4.3 REF_VEHICLE_OLD is saved as REF_VEHICLE,
1385 * and should be loaded like that */
1386 if (rt == REF_VEHICLE_OLD && !IsSavegameVersionBefore(4, 4)) {
1387 rt = REF_VEHICLE;
1390 /* No need to look up nullptr pointers, just return immediately */
1391 if (index == (rt == REF_VEHICLE_OLD ? 0xFFFF : 0)) return nullptr;
1393 /* Correct index. Old vehicles were saved differently:
1394 * invalid vehicle was 0xFFFF, now we use 0x0000 for everything invalid. */
1395 if (rt != REF_VEHICLE_OLD) index--;
1397 switch (rt) {
1398 case REF_ORDERLIST:
1399 if (OrderList::IsValidID(index)) return OrderList::Get(index);
1400 SlErrorCorrupt("Referencing invalid OrderList");
1402 case REF_ORDER:
1403 if (Order::IsValidID(index)) return Order::Get(index);
1404 /* in old versions, invalid order was used to mark end of order list */
1405 if (IsSavegameVersionBefore(5, 2)) return nullptr;
1406 SlErrorCorrupt("Referencing invalid Order");
1408 case REF_VEHICLE_OLD:
1409 case REF_VEHICLE:
1410 if (Vehicle::IsValidID(index)) return Vehicle::Get(index);
1411 SlErrorCorrupt("Referencing invalid Vehicle");
1413 case REF_TEMPLATE_VEHICLE:
1414 if (TemplateVehicle::IsValidID(index)) return TemplateVehicle::Get(index);
1415 SlErrorCorrupt("Referencing invalid TemplateVehicle");
1417 case REF_STATION:
1418 if (Station::IsValidID(index)) return Station::Get(index);
1419 SlErrorCorrupt("Referencing invalid Station");
1421 case REF_TOWN:
1422 if (Town::IsValidID(index)) return Town::Get(index);
1423 SlErrorCorrupt("Referencing invalid Town");
1425 case REF_ROADSTOPS:
1426 if (RoadStop::IsValidID(index)) return RoadStop::Get(index);
1427 SlErrorCorrupt("Referencing invalid RoadStop");
1429 case REF_DOCKS:
1430 if (Dock::IsValidID(index)) return Dock::Get(index);
1431 SlErrorCorrupt("Referencing invalid Dock");
1433 case REF_ENGINE_RENEWS:
1434 if (EngineRenew::IsValidID(index)) return EngineRenew::Get(index);
1435 SlErrorCorrupt("Referencing invalid EngineRenew");
1437 case REF_CARGO_PACKET:
1438 if (CargoPacket::IsValidID(index)) return CargoPacket::Get(index);
1439 SlErrorCorrupt("Referencing invalid CargoPacket");
1441 case REF_STORAGE:
1442 if (PersistentStorage::IsValidID(index)) return PersistentStorage::Get(index);
1443 SlErrorCorrupt("Referencing invalid PersistentStorage");
1445 case REF_LINK_GRAPH:
1446 if (LinkGraph::IsValidID(index)) return LinkGraph::Get(index);
1447 SlErrorCorrupt("Referencing invalid LinkGraph");
1449 case REF_LINK_GRAPH_JOB:
1450 if (LinkGraphJob::IsValidID(index)) return LinkGraphJob::Get(index);
1451 SlErrorCorrupt("Referencing invalid LinkGraphJob");
1453 default: NOT_REACHED();
1458 * Return the size in bytes of a list
1459 * @param list The std::list to find the size of
1461 template<typename PtrList>
1462 static inline size_t SlCalcListLen(const void *list)
1464 const PtrList *l = (const PtrList *)list;
1466 int type_size = IsSavegameVersionBefore(69) ? 2 : 4;
1467 /* Each entry is saved as type_size bytes, plus type_size bytes are used for the length
1468 * of the list */
1469 return l->size() * type_size + type_size;
1473 * Return the size in bytes of a list
1474 * @param list The std::list to find the size of
1476 template<typename PtrList>
1477 static inline size_t SlCalcVarListLen(const void *list, size_t item_size)
1479 const PtrList *l = (const PtrList *) list;
1480 /* Each entry is saved as item_size bytes, plus 4 bytes are used for the length
1481 * of the list */
1482 return l->size() * item_size + 4;
1487 * Save/Load a list.
1488 * @param list The list being manipulated
1489 * @param conv SLRefType type of the list (Vehicle *, Station *, etc)
1491 template<typename PtrList>
1492 static void SlList(void *list, SLRefType conv)
1494 /* Automatically calculate the length? */
1495 if (_sl.need_length != NL_NONE) {
1496 SlSetLength(SlCalcListLen<PtrList>(list));
1497 /* Determine length only? */
1498 if (_sl.need_length == NL_CALCLENGTH) return;
1501 PtrList *l = (PtrList *)list;
1503 switch (_sl.action) {
1504 case SLA_SAVE: {
1505 SlWriteUint32((uint32)l->size());
1507 typename PtrList::iterator iter;
1508 for (iter = l->begin(); iter != l->end(); ++iter) {
1509 void *ptr = *iter;
1510 SlWriteUint32((uint32)ReferenceToInt(ptr, conv));
1512 break;
1514 case SLA_LOAD_CHECK:
1515 case SLA_LOAD: {
1516 size_t length = IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1518 /* Load each reference and push to the end of the list */
1519 for (size_t i = 0; i < length; i++) {
1520 size_t data = IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1521 l->push_back((void *)data);
1523 break;
1525 case SLA_PTRS: {
1526 PtrList temp = *l;
1528 l->clear();
1529 typename PtrList::iterator iter;
1530 for (iter = temp.begin(); iter != temp.end(); ++iter) {
1531 void *ptr = IntToReference((size_t)*iter, conv);
1532 l->push_back(ptr);
1534 break;
1536 case SLA_NULL:
1537 l->clear();
1538 break;
1539 default: NOT_REACHED();
1544 * Save/Load a list.
1545 * @param list The list being manipulated
1546 * @param conv VarType type of the list
1548 template<typename PtrList>
1549 static void SlVarList(void *list, VarType conv)
1551 const size_t size_len = SlCalcConvMemLen(conv);
1552 /* Automatically calculate the length? */
1553 if (_sl.need_length != NL_NONE) {
1554 SlSetLength(SlCalcVarListLen<PtrList>(list, size_len));
1555 /* Determine length only? */
1556 if (_sl.need_length == NL_CALCLENGTH) return;
1559 PtrList *l = (PtrList *)list;
1561 switch (_sl.action) {
1562 case SLA_SAVE: {
1563 SlWriteUint32((uint32)l->size());
1565 typename PtrList::iterator iter;
1566 for (iter = l->begin(); iter != l->end(); ++iter) {
1567 SlSaveLoadConv(&(*iter), conv);
1569 break;
1571 case SLA_LOAD_CHECK:
1572 case SLA_LOAD: {
1573 size_t length = SlReadUint32();
1574 l->resize(length);
1576 typename PtrList::iterator iter;
1577 iter = l->begin();
1579 for (size_t i = 0; i < length; i++) {
1580 SlSaveLoadConv(&(*iter), conv);
1581 ++iter;
1583 break;
1585 case SLA_PTRS: break;
1586 case SLA_NULL:
1587 l->clear();
1588 break;
1589 default: NOT_REACHED();
1594 /** Are we going to save this object or not? */
1595 static inline bool SlIsObjectValidInSavegame(const SaveLoad *sld)
1597 if (_sl_version < sld->version_from || _sl_version > sld->version_to) return false;
1598 if (sld->conv & SLF_NOT_IN_SAVE) return false;
1600 return true;
1604 * Are we going to load this variable when loading a savegame or not?
1605 * @note If the variable is skipped it is skipped in the savegame
1606 * bytestream itself as well, so there is no need to skip it somewhere else
1608 static inline bool SlSkipVariableOnLoad(const SaveLoad *sld)
1610 if ((sld->conv & SLF_NO_NETWORK_SYNC) && _sl.action != SLA_SAVE && _networking && !_network_server) {
1611 SlSkipBytes(SlCalcConvMemLen(sld->conv) * sld->length);
1612 return true;
1615 return false;
1619 * Calculate the size of an object.
1620 * @param object to be measured
1621 * @param sld The SaveLoad description of the object so we know how to manipulate it
1622 * @return size of given object
1624 size_t SlCalcObjLength(const void *object, const SaveLoad *sld)
1626 size_t length = 0;
1628 /* Need to determine the length and write a length tag. */
1629 for (; sld->cmd != SL_END; sld++) {
1630 length += SlCalcObjMemberLength(object, sld);
1632 return length;
1635 size_t SlCalcObjMemberLength(const void *object, const SaveLoad *sld)
1637 assert(_sl.action == SLA_SAVE);
1639 switch (sld->cmd) {
1640 case SL_VAR:
1641 case SL_REF:
1642 case SL_ARR:
1643 case SL_STR:
1644 case SL_LST:
1645 case SL_DEQ:
1646 case SL_VEC:
1647 case SL_VARVEC:
1648 case SL_STDSTR:
1649 /* CONDITIONAL saveload types depend on the savegame version */
1650 if (!SlIsObjectValidInSavegame(sld)) break;
1652 switch (sld->cmd) {
1653 case SL_VAR: return SlCalcConvFileLen(sld->conv);
1654 case SL_REF: return SlCalcRefLen();
1655 case SL_ARR: return SlCalcArrayLen(sld->length, sld->conv);
1656 case SL_STR: return SlCalcStringLen(GetVariableAddress(object, sld), sld->length, sld->conv);
1657 case SL_LST: return SlCalcListLen<std::list<void *>>(GetVariableAddress(object, sld));
1658 case SL_DEQ: return SlCalcListLen<std::deque<void *>>(GetVariableAddress(object, sld));
1659 case SL_VEC: return SlCalcListLen<std::vector<void *>>(GetVariableAddress(object, sld));
1660 case SL_VARVEC: {
1661 const size_t size_len = SlCalcConvMemLen(sld->conv);
1662 switch (size_len) {
1663 case 1: return SlCalcVarListLen<std::vector<byte>>(GetVariableAddress(object, sld), 1);
1664 case 2: return SlCalcVarListLen<std::vector<uint16>>(GetVariableAddress(object, sld), 2);
1665 case 4: return SlCalcVarListLen<std::vector<uint32>>(GetVariableAddress(object, sld), 4);
1666 case 8: return SlCalcVarListLen<std::vector<uint64>>(GetVariableAddress(object, sld), 8);
1667 default: NOT_REACHED();
1670 case SL_STDSTR: return SlCalcStdStrLen(*static_cast<std::string *>(GetVariableAddress(object, sld)));
1671 default: NOT_REACHED();
1673 break;
1674 case SL_WRITEBYTE: return 1; // a byte is logically of size 1
1675 case SL_VEH_INCLUDE: return SlCalcObjLength(object, GetVehicleDescription(VEH_END));
1676 case SL_ST_INCLUDE: return SlCalcObjLength(object, GetBaseStationDescription());
1677 default: NOT_REACHED();
1679 return 0;
1682 #ifdef OTTD_ASSERT
1685 * Check whether the variable size of the variable in the saveload configuration
1686 * matches with the actual variable size.
1687 * @param sld The saveload configuration to test.
1689 static bool IsVariableSizeRight(const SaveLoad *sld)
1691 switch (sld->cmd) {
1692 case SL_VAR:
1693 switch (GetVarMemType(sld->conv)) {
1694 case SLE_VAR_BL:
1695 return sld->size == sizeof(bool);
1696 case SLE_VAR_I8:
1697 case SLE_VAR_U8:
1698 return sld->size == sizeof(int8);
1699 case SLE_VAR_I16:
1700 case SLE_VAR_U16:
1701 return sld->size == sizeof(int16);
1702 case SLE_VAR_I32:
1703 case SLE_VAR_U32:
1704 return sld->size == sizeof(int32);
1705 case SLE_VAR_I64:
1706 case SLE_VAR_U64:
1707 return sld->size == sizeof(int64);
1708 default:
1709 return sld->size == sizeof(void *);
1711 case SL_REF:
1712 /* These should all be pointer sized. */
1713 return sld->size == sizeof(void *);
1715 case SL_STR:
1716 /* These should be pointer sized, or fixed array. */
1717 return sld->size == sizeof(void *) || sld->size == sld->length;
1719 case SL_STDSTR:
1720 return sld->size == sizeof(std::string);
1722 default:
1723 return true;
1727 #endif /* OTTD_ASSERT */
1729 bool SlObjectMember(void *ptr, const SaveLoad *sld)
1731 #ifdef OTTD_ASSERT
1732 assert(IsVariableSizeRight(sld));
1733 #endif
1735 VarType conv = GB(sld->conv, 0, 8);
1736 switch (sld->cmd) {
1737 case SL_VAR:
1738 case SL_REF:
1739 case SL_ARR:
1740 case SL_STR:
1741 case SL_LST:
1742 case SL_DEQ:
1743 case SL_VEC:
1744 case SL_VARVEC:
1745 case SL_STDSTR:
1746 /* CONDITIONAL saveload types depend on the savegame version */
1747 if (!SlIsObjectValidInSavegame(sld)) return false;
1748 if (SlSkipVariableOnLoad(sld)) return false;
1750 switch (sld->cmd) {
1751 case SL_VAR: SlSaveLoadConv(ptr, conv); break;
1752 case SL_REF: // Reference variable, translate
1753 switch (_sl.action) {
1754 case SLA_SAVE:
1755 SlWriteUint32((uint32)ReferenceToInt(*(void **)ptr, (SLRefType)conv));
1756 break;
1757 case SLA_LOAD_CHECK:
1758 case SLA_LOAD:
1759 *(size_t *)ptr = IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1760 break;
1761 case SLA_PTRS:
1762 *(void **)ptr = IntToReference(*(size_t *)ptr, (SLRefType)conv);
1763 break;
1764 case SLA_NULL:
1765 *(void **)ptr = nullptr;
1766 break;
1767 default: NOT_REACHED();
1769 break;
1770 case SL_ARR: SlArray(ptr, sld->length, conv); break;
1771 case SL_STR: SlString(ptr, sld->length, sld->conv); break;
1772 case SL_LST: SlList<std::list<void *>>(ptr, (SLRefType)conv); break;
1773 case SL_DEQ: SlList<std::deque<void *>>(ptr, (SLRefType)conv); break;
1774 case SL_VEC: SlList<std::vector<void *>>(ptr, (SLRefType)conv); break;
1775 case SL_VARVEC: {
1776 const size_t size_len = SlCalcConvMemLen(sld->conv);
1777 switch (size_len) {
1778 case 1: SlVarList<std::vector<byte>>(ptr, conv); break;
1779 case 2: SlVarList<std::vector<uint16>>(ptr, conv); break;
1780 case 4: SlVarList<std::vector<uint32>>(ptr, conv); break;
1781 case 8: SlVarList<std::vector<uint64>>(ptr, conv); break;
1782 default: NOT_REACHED();
1784 break;
1786 case SL_STDSTR: SlStdString(*static_cast<std::string *>(ptr), sld->conv); break;
1787 default: NOT_REACHED();
1789 break;
1791 /* SL_WRITEBYTE translates a value of a variable to another one upon
1792 * saving or loading.
1793 * XXX - variable renaming abuse
1794 * game_value: the value of the variable ingame is abused by sld->version_from
1795 * file_value: the value of the variable in the savegame is abused by sld->version_to */
1796 case SL_WRITEBYTE:
1797 switch (_sl.action) {
1798 case SLA_SAVE: SlWriteByte(sld->version_to); break;
1799 case SLA_LOAD_CHECK:
1800 case SLA_LOAD: *(byte *)ptr = sld->version_from; break;
1801 case SLA_PTRS: break;
1802 case SLA_NULL: break;
1803 default: NOT_REACHED();
1805 break;
1807 /* SL_VEH_INCLUDE loads common code for vehicles */
1808 case SL_VEH_INCLUDE:
1809 SlObject(ptr, GetVehicleDescription(VEH_END));
1810 break;
1812 case SL_ST_INCLUDE:
1813 SlObject(ptr, GetBaseStationDescription());
1814 break;
1816 default: NOT_REACHED();
1818 return true;
1822 * Main SaveLoad function.
1823 * @param object The object that is being saved or loaded
1824 * @param sld The SaveLoad description of the object so we know how to manipulate it
1826 void SlObject(void *object, const SaveLoad *sld)
1828 /* Automatically calculate the length? */
1829 if (_sl.need_length != NL_NONE) {
1830 SlSetLength(SlCalcObjLength(object, sld));
1831 if (_sl.need_length == NL_CALCLENGTH) return;
1834 for (; sld->cmd != SL_END; sld++) {
1835 void *ptr = sld->global ? sld->address : GetVariableAddress(object, sld);
1836 SlObjectMember(ptr, sld);
1841 * Save or Load (a list of) global variables
1842 * @param sldg The global variable that is being loaded or saved
1844 void SlGlobList(const SaveLoadGlobVarList *sldg)
1846 SlObject(nullptr, (const SaveLoad*)sldg);
1850 * Do something of which I have no idea what it is :P
1851 * @param proc The callback procedure that is called
1852 * @param arg The variable that will be used for the callback procedure
1854 void SlAutolength(AutolengthProc *proc, void *arg)
1856 size_t offs;
1858 assert(_sl.action == SLA_SAVE);
1860 /* Tell it to calculate the length */
1861 _sl.need_length = NL_CALCLENGTH;
1862 _sl.obj_len = 0;
1863 proc(arg);
1865 /* Setup length */
1866 _sl.need_length = NL_WANTLENGTH;
1867 SlSetLength(_sl.obj_len);
1869 offs = _sl.dumper->GetSize() + _sl.obj_len;
1871 /* And write the stuff */
1872 proc(arg);
1874 if (offs != _sl.dumper->GetSize()) SlErrorCorrupt("Invalid chunk size");
1878 * Load a chunk of data (eg vehicles, stations, etc.)
1879 * @param ch The chunkhandler that will be used for the operation
1881 static void SlLoadChunk(const ChunkHandler *ch)
1883 byte m = SlReadByte();
1884 size_t len;
1885 size_t endoffs;
1887 _sl.block_mode = m;
1888 _sl.obj_len = 0;
1890 switch (m) {
1891 case CH_ARRAY:
1892 _sl.array_index = 0;
1893 ch->load_proc();
1894 if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
1895 break;
1896 case CH_SPARSE_ARRAY:
1897 ch->load_proc();
1898 if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
1899 break;
1900 default:
1901 if ((m & 0xF) == CH_RIFF) {
1902 /* Read length */
1903 len = (SlReadByte() << 16) | ((m >> 4) << 24);
1904 len += SlReadUint16();
1905 _sl.obj_len = len;
1906 endoffs = _sl.reader->GetSize() + len;
1907 ch->load_proc();
1908 if (_sl.reader->GetSize() != endoffs) SlErrorCorrupt("Invalid chunk size");
1909 } else {
1910 SlErrorCorrupt("Invalid chunk type");
1912 break;
1917 * Load a chunk of data for checking savegames.
1918 * If the chunkhandler is nullptr, the chunk is skipped.
1919 * @param ch The chunkhandler that will be used for the operation
1921 static void SlLoadCheckChunk(const ChunkHandler *ch)
1923 byte m = SlReadByte();
1924 size_t len;
1925 size_t endoffs;
1927 _sl.block_mode = m;
1928 _sl.obj_len = 0;
1930 switch (m) {
1931 case CH_ARRAY:
1932 _sl.array_index = 0;
1933 if (ch->load_check_proc) {
1934 ch->load_check_proc();
1935 } else {
1936 SlSkipArray();
1938 break;
1939 case CH_SPARSE_ARRAY:
1940 if (ch->load_check_proc) {
1941 ch->load_check_proc();
1942 } else {
1943 SlSkipArray();
1945 break;
1946 default:
1947 if ((m & 0xF) == CH_RIFF) {
1948 /* Read length */
1949 len = (SlReadByte() << 16) | ((m >> 4) << 24);
1950 len += SlReadUint16();
1951 _sl.obj_len = len;
1952 endoffs = _sl.reader->GetSize() + len;
1953 if (ch->load_check_proc) {
1954 ch->load_check_proc();
1955 } else {
1956 SlSkipBytes(len);
1958 if (_sl.reader->GetSize() != endoffs) SlErrorCorrupt("Invalid chunk size");
1959 } else {
1960 SlErrorCorrupt("Invalid chunk type");
1962 break;
1967 * Save a chunk of data (eg. vehicles, stations, etc.). Each chunk is
1968 * prefixed by an ID identifying it, followed by data, and terminator where appropriate
1969 * @param ch The chunkhandler that will be used for the operation
1971 static void SlSaveChunk(const ChunkHandler *ch)
1973 ChunkSaveLoadProc *proc = ch->save_proc;
1975 /* Don't save any chunk information if there is no save handler. */
1976 if (proc == nullptr) return;
1978 SlWriteUint32(ch->id);
1979 DEBUG(sl, 2, "Saving chunk %c%c%c%c", ch->id >> 24, ch->id >> 16, ch->id >> 8, ch->id);
1981 _sl.block_mode = ch->flags & CH_TYPE_MASK;
1982 switch (ch->flags & CH_TYPE_MASK) {
1983 case CH_RIFF:
1984 _sl.need_length = NL_WANTLENGTH;
1985 proc();
1986 break;
1987 case CH_ARRAY:
1988 _sl.last_array_index = 0;
1989 SlWriteByte(CH_ARRAY);
1990 proc();
1991 SlWriteArrayLength(0); // Terminate arrays
1992 break;
1993 case CH_SPARSE_ARRAY:
1994 SlWriteByte(CH_SPARSE_ARRAY);
1995 proc();
1996 SlWriteArrayLength(0); // Terminate arrays
1997 break;
1998 default: NOT_REACHED();
2002 /** Save all chunks */
2003 static void SlSaveChunks()
2005 FOR_ALL_CHUNK_HANDLERS(ch) {
2006 SlSaveChunk(ch);
2009 /* Terminator */
2010 SlWriteUint32(0);
2014 * Find the ChunkHandler that will be used for processing the found
2015 * chunk in the savegame or in memory
2016 * @param id the chunk in question
2017 * @return returns the appropriate chunkhandler
2019 static const ChunkHandler *SlFindChunkHandler(uint32 id)
2021 FOR_ALL_CHUNK_HANDLERS(ch) if (ch->id == id) return ch;
2022 return nullptr;
2025 /** Load all chunks */
2026 static void SlLoadChunks()
2028 uint32 id;
2029 const ChunkHandler *ch;
2031 for (id = SlReadUint32(); id != 0; id = SlReadUint32()) {
2032 DEBUG(sl, 2, "Loading chunk %c%c%c%c", id >> 24, id >> 16, id >> 8, id);
2034 ch = SlFindChunkHandler(id);
2035 if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2036 SlLoadChunk(ch);
2040 /** Load all chunks for savegame checking */
2041 static void SlLoadCheckChunks()
2043 uint32 id;
2044 const ChunkHandler *ch;
2046 for (id = SlReadUint32(); id != 0; id = SlReadUint32()) {
2047 DEBUG(sl, 2, "Loading chunk %c%c%c%c", id >> 24, id >> 16, id >> 8, id);
2049 ch = SlFindChunkHandler(id);
2050 if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2051 SlLoadCheckChunk(ch);
2055 /** Fix all pointers (convert index -> pointer) */
2056 static void SlFixPointers()
2058 _sl.action = SLA_PTRS;
2060 DEBUG(sl, 1, "Fixing pointers");
2062 FOR_ALL_CHUNK_HANDLERS(ch) {
2063 if (ch->ptrs_proc != nullptr) {
2064 DEBUG(sl, 2, "Fixing pointers for %c%c%c%c", ch->id >> 24, ch->id >> 16, ch->id >> 8, ch->id);
2065 ch->ptrs_proc();
2069 DEBUG(sl, 1, "All pointers fixed");
2071 assert(_sl.action == SLA_PTRS);
2075 /** Yes, simply reading from a file. */
2076 struct FileReader : LoadFilter {
2077 FILE *file; ///< The file to read from.
2078 long begin; ///< The begin of the file.
2081 * Create the file reader, so it reads from a specific file.
2082 * @param file The file to read from.
2084 FileReader(FILE *file) : LoadFilter(nullptr), file(file), begin(ftell(file))
2088 /** Make sure everything is cleaned up. */
2089 ~FileReader()
2091 if (this->file != nullptr) fclose(this->file);
2092 this->file = nullptr;
2094 /* Make sure we don't double free. */
2095 _sl.sf = nullptr;
2098 /* virtual */ size_t Read(byte *buf, size_t size)
2100 /* We're in the process of shutting down, i.e. in "failure" mode. */
2101 if (this->file == nullptr) return 0;
2103 return fread(buf, 1, size, this->file);
2106 /* virtual */ void Reset()
2108 clearerr(this->file);
2109 if (fseek(this->file, this->begin, SEEK_SET)) {
2110 DEBUG(sl, 1, "Could not reset the file reading");
2115 /** Yes, simply writing to a file. */
2116 struct FileWriter : SaveFilter {
2117 FILE *file; ///< The file to write to.
2120 * Create the file writer, so it writes to a specific file.
2121 * @param file The file to write to.
2123 FileWriter(FILE *file) : SaveFilter(nullptr), file(file)
2127 /** Make sure everything is cleaned up. */
2128 ~FileWriter()
2130 this->Finish();
2132 /* Make sure we don't double free. */
2133 _sl.sf = nullptr;
2136 /* virtual */ void Write(byte *buf, size_t size)
2138 /* We're in the process of shutting down, i.e. in "failure" mode. */
2139 if (this->file == nullptr) return;
2141 if (fwrite(buf, 1, size, this->file) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
2144 /* virtual */ void Finish()
2146 if (this->file != nullptr) fclose(this->file);
2147 this->file = nullptr;
2151 /*******************************************
2152 ********** START OF LZO CODE **************
2153 *******************************************/
2155 #ifdef WITH_LZO
2156 #include <lzo/lzo1x.h>
2158 /** Buffer size for the LZO compressor */
2159 static const uint LZO_BUFFER_SIZE = 8192;
2161 /** Filter using LZO compression. */
2162 struct LZOLoadFilter : LoadFilter {
2164 * Initialise this filter.
2165 * @param chain The next filter in this chain.
2167 LZOLoadFilter(LoadFilter *chain) : LoadFilter(chain)
2169 if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2172 /* virtual */ size_t Read(byte *buf, size_t ssize)
2174 assert(ssize >= LZO_BUFFER_SIZE);
2176 /* Buffer size is from the LZO docs plus the chunk header size. */
2177 byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32) * 2];
2178 uint32 tmp[2];
2179 uint32 size;
2180 lzo_uint len = ssize;
2182 /* Read header*/
2183 if (this->chain->Read((byte*)tmp, sizeof(tmp)) != sizeof(tmp)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE, "File read failed");
2185 /* Check if size is bad */
2186 ((uint32*)out)[0] = size = tmp[1];
2188 if (_sl_version != 0) {
2189 tmp[0] = TO_BE32(tmp[0]);
2190 size = TO_BE32(size);
2193 if (size >= sizeof(out)) SlErrorCorrupt("Inconsistent size");
2195 /* Read block */
2196 if (this->chain->Read(out + sizeof(uint32), size) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2198 /* Verify checksum */
2199 if (tmp[0] != lzo_adler32(0, out, size + sizeof(uint32))) SlErrorCorrupt("Bad checksum");
2201 /* Decompress */
2202 int ret = lzo1x_decompress_safe(out + sizeof(uint32) * 1, size, buf, &len, nullptr);
2203 if (ret != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2204 return len;
2208 /** Filter using LZO compression. */
2209 struct LZOSaveFilter : SaveFilter {
2211 * Initialise this filter.
2212 * @param chain The next filter in this chain.
2213 * @param compression_level The requested level of compression.
2215 LZOSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2217 if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2220 /* virtual */ void Write(byte *buf, size_t size)
2222 const lzo_bytep in = buf;
2223 /* Buffer size is from the LZO docs plus the chunk header size. */
2224 byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32) * 2];
2225 byte wrkmem[LZO1X_1_MEM_COMPRESS];
2226 lzo_uint outlen;
2228 do {
2229 /* Compress up to LZO_BUFFER_SIZE bytes at once. */
2230 lzo_uint len = size > LZO_BUFFER_SIZE ? LZO_BUFFER_SIZE : (lzo_uint)size;
2231 lzo1x_1_compress(in, len, out + sizeof(uint32) * 2, &outlen, wrkmem);
2232 ((uint32*)out)[1] = TO_BE32((uint32)outlen);
2233 ((uint32*)out)[0] = TO_BE32(lzo_adler32(0, out + sizeof(uint32), outlen + sizeof(uint32)));
2234 this->chain->Write(out, outlen + sizeof(uint32) * 2);
2236 /* Move to next data chunk. */
2237 size -= len;
2238 in += len;
2239 } while (size > 0);
2243 #endif /* WITH_LZO */
2245 /*********************************************
2246 ******** START OF NOCOMP CODE (uncompressed)*
2247 *********************************************/
2249 /** Filter without any compression. */
2250 struct NoCompLoadFilter : LoadFilter {
2252 * Initialise this filter.
2253 * @param chain The next filter in this chain.
2255 NoCompLoadFilter(LoadFilter *chain) : LoadFilter(chain)
2259 /* virtual */ size_t Read(byte *buf, size_t size)
2261 return this->chain->Read(buf, size);
2265 /** Filter without any compression. */
2266 struct NoCompSaveFilter : SaveFilter {
2268 * Initialise this filter.
2269 * @param chain The next filter in this chain.
2270 * @param compression_level The requested level of compression.
2272 NoCompSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2276 /* virtual */ void Write(byte *buf, size_t size)
2278 this->chain->Write(buf, size);
2282 /********************************************
2283 ********** START OF ZLIB CODE **************
2284 ********************************************/
2286 #if defined(WITH_ZLIB)
2287 #include <zlib.h>
2289 /** Filter using Zlib compression. */
2290 struct ZlibLoadFilter : LoadFilter {
2291 z_stream z; ///< Stream state we are reading from.
2292 byte fread_buf[MEMORY_CHUNK_SIZE]; ///< Buffer for reading from the file.
2295 * Initialise this filter.
2296 * @param chain The next filter in this chain.
2298 ZlibLoadFilter(LoadFilter *chain) : LoadFilter(chain)
2300 memset(&this->z, 0, sizeof(this->z));
2301 if (inflateInit(&this->z) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2304 /** Clean everything up. */
2305 ~ZlibLoadFilter()
2307 inflateEnd(&this->z);
2310 /* virtual */ size_t Read(byte *buf, size_t size)
2312 this->z.next_out = buf;
2313 this->z.avail_out = (uint)size;
2315 do {
2316 /* read more bytes from the file? */
2317 if (this->z.avail_in == 0) {
2318 this->z.next_in = this->fread_buf;
2319 this->z.avail_in = (uint)this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2322 /* inflate the data */
2323 int r = inflate(&this->z, 0);
2324 if (r == Z_STREAM_END) break;
2326 if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "inflate() failed");
2327 } while (this->z.avail_out != 0);
2329 return size - this->z.avail_out;
2333 /** Filter using Zlib compression. */
2334 struct ZlibSaveFilter : SaveFilter {
2335 z_stream z; ///< Stream state we are writing to.
2338 * Initialise this filter.
2339 * @param chain The next filter in this chain.
2340 * @param compression_level The requested level of compression.
2342 ZlibSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2344 memset(&this->z, 0, sizeof(this->z));
2345 if (deflateInit(&this->z, compression_level) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2348 /** Clean up what we allocated. */
2349 ~ZlibSaveFilter()
2351 deflateEnd(&this->z);
2355 * Helper loop for writing the data.
2356 * @param p The bytes to write.
2357 * @param len Amount of bytes to write.
2358 * @param mode Mode for deflate.
2360 void WriteLoop(byte *p, size_t len, int mode)
2362 byte buf[MEMORY_CHUNK_SIZE]; // output buffer
2363 uint n;
2364 this->z.next_in = p;
2365 this->z.avail_in = (uInt)len;
2366 do {
2367 this->z.next_out = buf;
2368 this->z.avail_out = sizeof(buf);
2371 * For the poor next soul who sees many valgrind warnings of the
2372 * "Conditional jump or move depends on uninitialised value(s)" kind:
2373 * According to the author of zlib it is not a bug and it won't be fixed.
2374 * http://groups.google.com/group/comp.compression/browse_thread/thread/b154b8def8c2a3ef/cdf9b8729ce17ee2
2375 * [Mark Adler, Feb 24 2004, 'zlib-1.2.1 valgrind warnings' in the newsgroup comp.compression]
2377 int r = deflate(&this->z, mode);
2379 /* bytes were emitted? */
2380 if ((n = sizeof(buf) - this->z.avail_out) != 0) {
2381 this->chain->Write(buf, n);
2383 if (r == Z_STREAM_END) break;
2385 if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "zlib returned error code");
2386 } while (this->z.avail_in || !this->z.avail_out);
2389 /* virtual */ void Write(byte *buf, size_t size)
2391 this->WriteLoop(buf, size, 0);
2394 /* virtual */ void Finish()
2396 this->WriteLoop(nullptr, 0, Z_FINISH);
2397 this->chain->Finish();
2401 #endif /* WITH_ZLIB */
2403 /********************************************
2404 ********** START OF LZMA CODE **************
2405 ********************************************/
2407 #if defined(WITH_LZMA)
2408 #include <lzma.h>
2411 * Have a copy of an initialised LZMA stream. We need this as it's
2412 * impossible to "re"-assign LZMA_STREAM_INIT to a variable in some
2413 * compilers, i.e. LZMA_STREAM_INIT can't be used to set something.
2414 * This var has to be used instead.
2416 static const lzma_stream _lzma_init = LZMA_STREAM_INIT;
2418 /** Filter without any compression. */
2419 struct LZMALoadFilter : LoadFilter {
2420 lzma_stream lzma; ///< Stream state that we are reading from.
2421 byte fread_buf[MEMORY_CHUNK_SIZE]; ///< Buffer for reading from the file.
2424 * Initialise this filter.
2425 * @param chain The next filter in this chain.
2427 LZMALoadFilter(LoadFilter *chain) : LoadFilter(chain), lzma(_lzma_init)
2429 /* Allow saves up to 256 MB uncompressed */
2430 if (lzma_auto_decoder(&this->lzma, 1 << 28, 0) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2433 /** Clean everything up. */
2434 ~LZMALoadFilter()
2436 lzma_end(&this->lzma);
2439 /* virtual */ size_t Read(byte *buf, size_t size)
2441 this->lzma.next_out = buf;
2442 this->lzma.avail_out = size;
2444 do {
2445 /* read more bytes from the file? */
2446 if (this->lzma.avail_in == 0) {
2447 this->lzma.next_in = this->fread_buf;
2448 this->lzma.avail_in = this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2451 /* inflate the data */
2452 lzma_ret r = lzma_code(&this->lzma, LZMA_RUN);
2453 if (r == LZMA_STREAM_END) break;
2454 if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2455 } while (this->lzma.avail_out != 0);
2457 return size - this->lzma.avail_out;
2461 /** Filter using LZMA compression. */
2462 struct LZMASaveFilter : SaveFilter {
2463 lzma_stream lzma; ///< Stream state that we are writing to.
2466 * Initialise this filter.
2467 * @param chain The next filter in this chain.
2468 * @param compression_level The requested level of compression.
2470 LZMASaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain), lzma(_lzma_init)
2472 if (lzma_easy_encoder(&this->lzma, compression_level, LZMA_CHECK_CRC32) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2475 /** Clean up what we allocated. */
2476 ~LZMASaveFilter()
2478 lzma_end(&this->lzma);
2482 * Helper loop for writing the data.
2483 * @param p The bytes to write.
2484 * @param len Amount of bytes to write.
2485 * @param action Action for lzma_code.
2487 void WriteLoop(byte *p, size_t len, lzma_action action)
2489 byte buf[MEMORY_CHUNK_SIZE]; // output buffer
2490 size_t n;
2491 this->lzma.next_in = p;
2492 this->lzma.avail_in = len;
2493 do {
2494 this->lzma.next_out = buf;
2495 this->lzma.avail_out = sizeof(buf);
2497 lzma_ret r = lzma_code(&this->lzma, action);
2499 /* bytes were emitted? */
2500 if ((n = sizeof(buf) - this->lzma.avail_out) != 0) {
2501 this->chain->Write(buf, n);
2503 if (r == LZMA_STREAM_END) break;
2504 if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2505 } while (this->lzma.avail_in || !this->lzma.avail_out);
2508 /* virtual */ void Write(byte *buf, size_t size)
2510 this->WriteLoop(buf, size, LZMA_RUN);
2513 /* virtual */ void Finish()
2515 this->WriteLoop(nullptr, 0, LZMA_FINISH);
2516 this->chain->Finish();
2520 #endif /* WITH_LZMA */
2522 /*******************************************
2523 ************* END OF CODE *****************
2524 *******************************************/
2526 /** The format for a reader/writer type of a savegame */
2527 struct SaveLoadFormat {
2528 const char *name; ///< name of the compressor/decompressor (debug-only)
2529 uint32 tag; ///< the 4-letter tag by which it is identified in the savegame
2531 LoadFilter *(*init_load)(LoadFilter *chain); ///< Constructor for the load filter.
2532 SaveFilter *(*init_write)(SaveFilter *chain, byte compression); ///< Constructor for the save filter.
2534 byte min_compression; ///< the minimum compression level of this format
2535 byte default_compression; ///< the default compression level of this format
2536 byte max_compression; ///< the maximum compression level of this format
2539 /** The different saveload formats known/understood by OpenTTD. */
2540 static const SaveLoadFormat _saveload_formats[] = {
2541 #if defined(WITH_LZO)
2542 /* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
2543 {"lzo", TO_BE32X('OTTD'), CreateLoadFilter<LZOLoadFilter>, CreateSaveFilter<LZOSaveFilter>, 0, 0, 0},
2544 #else
2545 {"lzo", TO_BE32X('OTTD'), nullptr, nullptr, 0, 0, 0},
2546 #endif
2547 /* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
2548 {"none", TO_BE32X('OTTN'), CreateLoadFilter<NoCompLoadFilter>, CreateSaveFilter<NoCompSaveFilter>, 0, 0, 0},
2549 #if defined(WITH_ZLIB)
2550 /* After level 6 the speed reduction is significant (1.5x to 2.5x slower per level), but the reduction in filesize is
2551 * fairly insignificant (~1% for each step). Lower levels become ~5-10% bigger by each level than level 6 while level
2552 * 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
2553 {"zlib", TO_BE32X('OTTZ'), CreateLoadFilter<ZlibLoadFilter>, CreateSaveFilter<ZlibSaveFilter>, 0, 6, 9},
2554 #else
2555 {"zlib", TO_BE32X('OTTZ'), nullptr, nullptr, 0, 0, 0},
2556 #endif
2557 #if defined(WITH_LZMA)
2558 /* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
2559 * Higher compression levels are possible, and might improve savegame size by up to 25%, but are also up to 10 times slower.
2560 * The next significant reduction in file size is at level 4, but that is already 4 times slower. Level 3 is primarily 50%
2561 * slower while not improving the filesize, while level 0 and 1 are faster, but don't reduce savegame size much.
2562 * It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
2563 {"lzma", TO_BE32X('OTTX'), CreateLoadFilter<LZMALoadFilter>, CreateSaveFilter<LZMASaveFilter>, 0, 2, 9},
2564 #else
2565 {"lzma", TO_BE32X('OTTX'), nullptr, nullptr, 0, 0, 0},
2566 #endif
2570 * Return the savegameformat of the game. Whether it was created with ZLIB compression
2571 * uncompressed, or another type
2572 * @param s Name of the savegame format. If nullptr it picks the first available one
2573 * @param compression_level Output for telling what compression level we want.
2574 * @return Pointer to SaveLoadFormat struct giving all characteristics of this type of savegame
2576 static const SaveLoadFormat *GetSavegameFormat(char *s, byte *compression_level)
2578 const SaveLoadFormat *def = lastof(_saveload_formats);
2580 /* find default savegame format, the highest one with which files can be written */
2581 while (!def->init_write) def--;
2583 if (!StrEmpty(s)) {
2584 /* Get the ":..." of the compression level out of the way */
2585 char *complevel = strrchr(s, ':');
2586 if (complevel != nullptr) *complevel = '\0';
2588 for (const SaveLoadFormat *slf = &_saveload_formats[0]; slf != endof(_saveload_formats); slf++) {
2589 if (slf->init_write != nullptr && strcmp(s, slf->name) == 0) {
2590 *compression_level = slf->default_compression;
2591 if (complevel != nullptr) {
2592 /* There is a compression level in the string.
2593 * First restore the : we removed to do proper name matching,
2594 * then move the the begin of the actual version. */
2595 *complevel = ':';
2596 complevel++;
2598 /* Get the version and determine whether all went fine. */
2599 char *end;
2600 long level = strtol(complevel, &end, 10);
2601 if (end == complevel || level != Clamp(level, slf->min_compression, slf->max_compression)) {
2602 SetDParamStr(0, complevel);
2603 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_LEVEL, WL_CRITICAL);
2604 } else {
2605 *compression_level = level;
2608 return slf;
2612 SetDParamStr(0, s);
2613 SetDParamStr(1, def->name);
2614 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM, WL_CRITICAL);
2616 /* Restore the string by adding the : back */
2617 if (complevel != nullptr) *complevel = ':';
2619 *compression_level = def->default_compression;
2620 return def;
2623 /* actual loader/saver function */
2624 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
2625 extern bool AfterLoadGame();
2626 extern bool LoadOldSaveGame(const char *file);
2629 * Clear/free saveload state.
2631 static inline void ClearSaveLoadState()
2633 delete _sl.dumper;
2634 _sl.dumper = nullptr;
2636 delete _sl.sf;
2637 _sl.sf = nullptr;
2639 delete _sl.reader;
2640 _sl.reader = nullptr;
2642 delete _sl.lf;
2643 _sl.lf = nullptr;
2647 * Update the gui accordingly when starting saving
2648 * and set locks on saveload. Also turn off fast-forward cause with that
2649 * saving takes Aaaaages
2651 static void SaveFileStart()
2653 _sl.ff_state = _fast_forward;
2654 _fast_forward = 0;
2655 SetMouseCursorBusy(true);
2657 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SAVELOAD_START);
2658 _sl.saveinprogress = true;
2661 /** Update the gui accordingly when saving is done and release locks on saveload. */
2662 static void SaveFileDone()
2664 if (_game_mode != GM_MENU) _fast_forward = _sl.ff_state;
2665 SetMouseCursorBusy(false);
2667 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SAVELOAD_FINISH);
2668 _sl.saveinprogress = false;
2671 /** Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friends) */
2672 void SetSaveLoadError(StringID str)
2674 _sl.error_str = str;
2677 /** Get the string representation of the error message */
2678 const char *GetSaveLoadErrorString()
2680 SetDParam(0, _sl.error_str);
2681 SetDParamStr(1, _sl.extra_msg);
2683 static char err_str[512];
2684 GetString(err_str, _sl.action == SLA_SAVE ? STR_ERROR_GAME_SAVE_FAILED : STR_ERROR_GAME_LOAD_FAILED, lastof(err_str));
2685 return err_str;
2688 /** Show a gui message when saving has failed */
2689 static void SaveFileError()
2691 SetDParamStr(0, GetSaveLoadErrorString());
2692 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
2693 SaveFileDone();
2697 * We have written the whole game into memory, _memory_savegame, now find
2698 * and appropriate compressor and start writing to file.
2700 static SaveOrLoadResult SaveFileToDisk(bool threaded)
2702 try {
2703 byte compression;
2704 const SaveLoadFormat *fmt = GetSavegameFormat(_savegame_format, &compression);
2706 /* We have written our stuff to memory, now write it to file! */
2707 uint32 hdr[2] = { fmt->tag, TO_BE32(SAVEGAME_VERSION << 16) };
2708 _sl.sf->Write((byte*)hdr, sizeof(hdr));
2710 _sl.sf = fmt->init_write(_sl.sf, compression);
2711 _sl.dumper->Flush(_sl.sf);
2713 ClearSaveLoadState();
2715 if (threaded) SetAsyncSaveFinish(SaveFileDone);
2717 return SL_OK;
2718 } catch (...) {
2719 ClearSaveLoadState();
2721 AsyncSaveFinishProc asfp = SaveFileDone;
2723 /* We don't want to shout when saving is just
2724 * cancelled due to a client disconnecting. */
2725 if (_sl.error_str != STR_NETWORK_ERROR_LOSTCONNECTION) {
2726 /* Skip the "colour" character */
2727 DEBUG(sl, 0, "%s", GetSaveLoadErrorString() + 3);
2728 asfp = SaveFileError;
2731 if (threaded) {
2732 SetAsyncSaveFinish(asfp);
2733 } else {
2734 asfp();
2736 return SL_ERROR;
2740 /** Thread run function for saving the file to disk. */
2741 static void SaveFileToDiskThread(void *arg)
2743 SaveFileToDisk(true);
2746 void WaitTillSaved()
2748 if (_save_thread == nullptr) return;
2750 _save_thread->Join();
2751 delete _save_thread;
2752 _save_thread = nullptr;
2754 /* Make sure every other state is handled properly as well. */
2755 ProcessAsyncSaveFinish();
2759 * Actually perform the saving of the savegame.
2760 * General tactics is to first save the game to memory, then write it to file
2761 * using the writer, either in threaded mode if possible, or single-threaded.
2762 * @param writer The filter to write the savegame to.
2763 * @param threaded Whether to try to perform the saving asynchronously.
2764 * @return Return the result of the action. #SL_OK or #SL_ERROR
2766 static SaveOrLoadResult DoSave(SaveFilter *writer, bool threaded)
2768 assert(!_sl.saveinprogress);
2770 _sl.dumper = new MemoryDumper();
2771 _sl.sf = writer;
2773 _sl_version = SAVEGAME_VERSION;
2775 SaveViewportBeforeSaveGame();
2776 SlSaveChunks();
2778 SaveFileStart();
2779 if (!threaded || !ThreadObject::New(&SaveFileToDiskThread, nullptr, &_save_thread, "ottd:savegame")) {
2780 if (threaded) DEBUG(sl, 1, "Cannot create savegame thread, reverting to single-threaded mode...");
2782 SaveOrLoadResult result = SaveFileToDisk(false);
2783 SaveFileDone();
2785 return result;
2788 return SL_OK;
2792 * Save the game using a (writer) filter.
2793 * @param writer The filter to write the savegame to.
2794 * @param threaded Whether to try to perform the saving asynchronously.
2795 * @return Return the result of the action. #SL_OK or #SL_ERROR
2797 SaveOrLoadResult SaveWithFilter(SaveFilter *writer, bool threaded)
2799 try {
2800 _sl.action = SLA_SAVE;
2801 return DoSave(writer, threaded);
2802 } catch (...) {
2803 ClearSaveLoadState();
2804 return SL_ERROR;
2809 * Actually perform the loading of a "non-old" savegame.
2810 * @param reader The filter to read the savegame from.
2811 * @param load_check Whether to perform the checking ("preview") or actually load the game.
2812 * @return Return the result of the action. #SL_OK or #SL_REINIT ("unload" the game)
2814 static SaveOrLoadResult DoLoad(LoadFilter *reader, bool load_check)
2816 _sl.lf = reader;
2818 if (load_check) {
2819 /* Clear previous check data */
2820 _load_check_data.Clear();
2821 /* Mark SL_LOAD_CHECK as supported for this savegame. */
2822 _load_check_data.checkable = true;
2825 uint32 hdr[2];
2826 if (_sl.lf->Read((byte*)hdr, sizeof(hdr)) != sizeof(hdr)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2828 /* see if we have any loader for this type. */
2829 const SaveLoadFormat *fmt = _saveload_formats;
2830 for (;;) {
2831 /* No loader found, treat as version 0 and use LZO format */
2832 if (fmt == endof(_saveload_formats)) {
2833 DEBUG(sl, 0, "Unknown savegame type, trying to load it as the buggy format");
2834 _sl.lf->Reset();
2835 _sl_version = 0;
2836 _sl_minor_version = 0;
2838 /* Try to find the LZO savegame format; it uses 'OTTD' as tag. */
2839 fmt = _saveload_formats;
2840 for (;;) {
2841 if (fmt == endof(_saveload_formats)) {
2842 /* Who removed LZO support? Bad bad boy! */
2843 NOT_REACHED();
2845 if (fmt->tag == TO_BE32X('OTTD')) break;
2846 fmt++;
2848 break;
2851 if (fmt->tag == hdr[0]) {
2852 /* check version number */
2853 _sl_version = TO_BE32(hdr[1]) >> 16;
2854 /* Minor is not used anymore from version 18.0, but it is still needed
2855 * in versions before that (4 cases) which can't be removed easy.
2856 * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */
2857 _sl_minor_version = (TO_BE32(hdr[1]) >> 8) & 0xFF;
2859 DEBUG(sl, 1, "Loading savegame version %d", _sl_version);
2861 /* Is the version higher than the current? */
2862 if (_sl_version > SAVEGAME_VERSION) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME);
2863 break;
2866 fmt++;
2869 /* loader for this savegame type is not implemented? */
2870 if (fmt->init_load == nullptr) {
2871 char err_str[64];
2872 seprintf(err_str, lastof(err_str), "Loader for '%s' is not available.", fmt->name);
2873 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, err_str);
2876 _sl.lf = fmt->init_load(_sl.lf);
2877 _sl.reader = new ReadBuffer(_sl.lf);
2878 _next_offs = 0;
2880 if (!load_check) {
2881 /* Old maps were hardcoded to 256x256 and thus did not contain
2882 * any mapsize information. Pre-initialize to 256x256 to not to
2883 * confuse old games */
2884 InitializeGame(256, 256, true, true);
2886 GamelogReset();
2888 if (IsSavegameVersionBefore(4)) {
2890 * NewGRFs were introduced between 0.3,4 and 0.3.5, which both
2891 * shared savegame version 4. Anything before that 'obviously'
2892 * does not have any NewGRFs. Between the introduction and
2893 * savegame version 41 (just before 0.5) the NewGRF settings
2894 * were not stored in the savegame and they were loaded by
2895 * using the settings from the main menu.
2896 * So, to recap:
2897 * - savegame version < 4: do not load any NewGRFs.
2898 * - savegame version >= 41: load NewGRFs from savegame, which is
2899 * already done at this stage by
2900 * overwriting the main menu settings.
2901 * - other savegame versions: use main menu settings.
2903 * This means that users *can* crash savegame version 4..40
2904 * savegames if they set incompatible NewGRFs in the main menu,
2905 * but can't crash anymore for savegame version < 4 savegames.
2907 * Note: this is done here because AfterLoadGame is also called
2908 * for TTO/TTD/TTDP savegames which have their own NewGRF logic.
2910 ClearGRFConfigList(&_grfconfig);
2914 if (load_check) {
2915 /* Load chunks into _load_check_data.
2916 * No pools are loaded. References are not possible, and thus do not need resolving. */
2917 SlLoadCheckChunks();
2918 } else {
2919 /* Load chunks and resolve references */
2920 SlLoadChunks();
2921 SlFixPointers();
2924 ClearSaveLoadState();
2926 _savegame_type = SGT_OTTD;
2928 if (load_check) {
2929 /* The only part from AfterLoadGame() we need */
2930 _load_check_data.grf_compatibility = IsGoodGRFConfigList(_load_check_data.grfconfig);
2931 } else {
2932 GamelogStartAction(GLAT_LOAD);
2934 /* After loading fix up savegame for any internal changes that
2935 * might have occurred since then. If it fails, load back the old game. */
2936 if (!AfterLoadGame()) {
2937 GamelogStopAction();
2938 return SL_REINIT;
2941 GamelogStopAction();
2944 return SL_OK;
2948 * Load the game using a (reader) filter.
2949 * @param reader The filter to read the savegame from.
2950 * @return Return the result of the action. #SL_OK or #SL_REINIT ("unload" the game)
2952 SaveOrLoadResult LoadWithFilter(LoadFilter *reader)
2954 try {
2955 _sl.action = SLA_LOAD;
2956 return DoLoad(reader, false);
2957 } catch (...) {
2958 ClearSaveLoadState();
2959 return SL_REINIT;
2964 * Main Save or Load function where the high-level saveload functions are
2965 * handled. It opens the savegame, selects format and checks versions
2966 * @param filename The name of the savegame being created/loaded
2967 * @param mode Save or load mode. Load can also be a TTD(Patch) game. Use #SL_LOAD, #SL_OLD_LOAD, #SL_LOAD_CHECK, or #SL_SAVE.
2968 * @param sb The sub directory to save the savegame in
2969 * @param threaded True when threaded saving is allowed
2970 * @return Return the result of the action. #SL_OK, #SL_ERROR, or #SL_REINIT ("unload" the game)
2972 SaveOrLoadResult SaveOrLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
2974 /* An instance of saving is already active, so don't go saving again */
2975 if (_sl.saveinprogress && fop == SLO_SAVE && dft == DFT_GAME_FILE && threaded) {
2976 /* if not an autosave, but a user action, show error message */
2977 if (!_do_autosave) ShowErrorMessage(STR_ERROR_SAVE_STILL_IN_PROGRESS, INVALID_STRING_ID, WL_ERROR);
2978 return SL_OK;
2980 WaitTillSaved();
2982 try {
2983 /* Load a TTDLX or TTDPatch game */
2984 if (fop == SLO_LOAD && dft == DFT_OLD_GAME_FILE) {
2985 InitializeGame(256, 256, true, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
2987 /* TTD/TTO savegames have no NewGRFs, TTDP savegame have them
2988 * and if so a new NewGRF list will be made in LoadOldSaveGame.
2989 * Note: this is done here because AfterLoadGame is also called
2990 * for OTTD savegames which have their own NewGRF logic. */
2991 ClearGRFConfigList(&_grfconfig);
2992 GamelogReset();
2993 if (!LoadOldSaveGame(filename)) return SL_REINIT;
2994 _sl_version = 0;
2995 _sl_minor_version = 0;
2996 GamelogStartAction(GLAT_LOAD);
2997 if (!AfterLoadGame()) {
2998 GamelogStopAction();
2999 return SL_REINIT;
3001 GamelogStopAction();
3002 return SL_OK;
3005 assert(dft == DFT_GAME_FILE);
3006 switch (fop) {
3007 case SLO_CHECK:
3008 _sl.action = SLA_LOAD_CHECK;
3009 break;
3011 case SLO_LOAD:
3012 _sl.action = SLA_LOAD;
3013 break;
3015 case SLO_SAVE:
3016 _sl.action = SLA_SAVE;
3017 break;
3019 default: NOT_REACHED();
3022 FILE *fh = (fop == SLO_SAVE) ? FioFOpenFile(filename, "wb", sb) : FioFOpenFile(filename, "rb", sb);
3024 /* Make it a little easier to load savegames from the console */
3025 if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SAVE_DIR);
3026 if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", BASE_DIR);
3027 if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SCENARIO_DIR);
3029 if (fh == nullptr) {
3030 SlError(fop == SLO_SAVE ? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE : STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3033 if (fop == SLO_SAVE) { // SAVE game
3034 DEBUG(desync, 1, "save: %08x; %02x; %s", _date, _date_fract, filename);
3035 if (_network_server || !_settings_client.gui.threaded_saves) threaded = false;
3037 return DoSave(new FileWriter(fh), threaded);
3040 /* LOAD game */
3041 assert(fop == SLO_LOAD || fop == SLO_CHECK);
3042 DEBUG(desync, 1, "load: %s", filename);
3043 return DoLoad(new FileReader(fh), fop == SLO_CHECK);
3044 } catch (...) {
3045 /* This code may be executed both for old and new save games. */
3046 ClearSaveLoadState();
3048 /* Skip the "colour" character */
3049 if (fop != SLO_CHECK) DEBUG(sl, 0, "%s", GetSaveLoadErrorString() + 3);
3051 /* A saver/loader exception!! reinitialize all variables to prevent crash! */
3052 return (fop == SLO_LOAD) ? SL_REINIT : SL_ERROR;
3056 /** Do a save when exiting the game (_settings_client.gui.autosave_on_exit) */
3057 void DoExitSave()
3059 SaveOrLoad("exit.sav", SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR);
3063 * Fill the buffer with the default name for a savegame *or* screenshot.
3064 * @param buf the buffer to write to.
3065 * @param last the last element in the buffer.
3067 void GenerateDefaultSaveName(char *buf, const char *last)
3069 /* Check if we have a name for this map, which is the name of the first
3070 * available company. When there's no company available we'll use
3071 * 'Spectator' as "company" name. */
3072 CompanyID cid = _local_company;
3073 if (!Company::IsValidID(cid)) {
3074 const Company *c;
3075 FOR_ALL_COMPANIES(c) {
3076 cid = c->index;
3077 break;
3081 SetDParam(0, cid);
3083 /* Insert current date */
3084 switch (_settings_client.gui.date_format_in_default_names) {
3085 case 0: SetDParam(1, STR_JUST_DATE_LONG); break;
3086 case 1: SetDParam(1, STR_JUST_DATE); break;
3087 case 2: SetDParam(1, STR_JUST_DATE_ISO); break;
3088 default: NOT_REACHED();
3090 SetDParam(2, _date);
3092 /* Get the correct string (special string for when there's not company) */
3093 GetString(buf, !Company::IsValidID(cid) ? STR_SAVEGAME_NAME_SPECTATOR : STR_SAVEGAME_NAME_DEFAULT, last);
3094 SanitizeFilename(buf);
3098 * Set the mode and file type of the file to save or load based on the type of file entry at the file system.
3099 * @param ft Type of file entry of the file system.
3101 void FileToSaveLoad::SetMode(FiosType ft)
3103 this->SetMode(SLO_LOAD, GetAbstractFileType(ft), GetDetailedFileType(ft));
3107 * Set the mode and file type of the file to save or load.
3108 * @param fop File operation being performed.
3109 * @param aft Abstract file type.
3110 * @param dft Detailed file type.
3112 void FileToSaveLoad::SetMode(SaveLoadOperation fop, AbstractFileType aft, DetailedFileType dft)
3114 if (aft == FT_INVALID || aft == FT_NONE) {
3115 this->file_op = SLO_INVALID;
3116 this->detail_ftype = DFT_INVALID;
3117 this->abstract_ftype = FT_INVALID;
3118 return;
3121 this->file_op = fop;
3122 this->detail_ftype = dft;
3123 this->abstract_ftype = aft;
3127 * Set the name of the file.
3128 * @param name Name of the file.
3130 void FileToSaveLoad::SetName(const char *name)
3132 strecpy(this->name, name, lastof(this->name));
3136 * Set the title of the file.
3137 * @param title Title of the file.
3139 void FileToSaveLoad::SetTitle(const char *title)
3141 strecpy(this->title, title, lastof(this->title));
3144 #if 0
3146 * Function to get the type of the savegame by looking at the file header.
3147 * NOTICE: Not used right now, but could be used if extensions of savegames are garbled
3148 * @param file Savegame to be checked
3149 * @return SL_OLD_LOAD or SL_LOAD of the file
3151 int GetSavegameType(char *file)
3153 const SaveLoadFormat *fmt;
3154 uint32 hdr;
3155 FILE *f;
3156 int mode = SL_OLD_LOAD;
3158 f = fopen(file, "rb");
3159 if (fread(&hdr, sizeof(hdr), 1, f) != 1) {
3160 DEBUG(sl, 0, "Savegame is obsolete or invalid format");
3161 mode = SL_LOAD; // don't try to get filename, just show name as it is written
3162 } else {
3163 /* see if we have any loader for this type. */
3164 for (fmt = _saveload_formats; fmt != endof(_saveload_formats); fmt++) {
3165 if (fmt->tag == hdr) {
3166 mode = SL_LOAD; // new type of savegame
3167 break;
3172 fclose(f);
3173 return mode;
3175 #endif