OpenTTD Source: src/saveload/saveload.cpp Source File

OpenTTD Source 14.0-RC3

saveload.cpp
Go to the documentation of this file.
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
23 #include "../stdafx.h"
24 #include "../debug.h"
25 #include "../station_base.h"
26 #include "../thread.h"
27 #include "../town.h"
28 #include "../network/network.h"
29 #include "../window_func.h"
30 #include "../strings_func.h"
31 #include "../core/endian_func.hpp"
32 #include "../vehicle_base.h"
33 #include "../company_func.h"
34 #include "../timer/timer_game_economy.h"
35 #include "../autoreplace_base.h"
36 #include "../roadstop_base.h"
37 #include "../linkgraph/linkgraph.h"
38 #include "../linkgraph/linkgraphjob.h"
39 #include "../statusbar_gui.h"
40 #include "../fileio_func.h"
41 #include "../gamelog.h"
42 #include "../string_func.h"
43 #include "../fios.h"
44 #include "../error.h"
45 #include <atomic>
46 #ifdef __EMSCRIPTEN__
47 # include <emscripten.h>
48 #endif
49
50 #include "table/strings.h"
51
52 #include "saveload_internal.h"
53 #include "saveload_filter.h"
54
55 #include "../safeguards.h"
56
57 extern const SaveLoadVersion SAVEGAME_VERSION = (SaveLoadVersion)(SL_MAX_VERSION - 1);
58
59 SavegameType _savegame_type;
60 FileToSaveLoad _file_to_saveload;
61
62 uint32_t _ttdp_version;
63 SaveLoadVersion _sl_version;
64 byte _sl_minor_version;
65 std::string _savegame_format;
66 bool _do_autosave;
67
69 enum SaveLoadAction {
70 SLA_LOAD,
71 SLA_SAVE,
72 SLA_PTRS,
73 SLA_NULL,
74 SLA_LOAD_CHECK,
75 };
76
77 enum NeedLength {
78 NL_NONE = 0,
79 NL_WANTLENGTH = 1,
80 NL_CALCLENGTH = 2,
81 };
82
84 static const size_t MEMORY_CHUNK_SIZE = 128 * 1024;
85
87 struct ReadBuffer {
88 byte buf[MEMORY_CHUNK_SIZE];
89 byte *bufp;
90 byte *bufe;
91 std::shared_ptr<LoadFilter> reader;
92 size_t read;
93
98 ReadBuffer(std::shared_ptr<LoadFilter> reader) : bufp(nullptr), bufe(nullptr), reader(reader), read(0)
99 {
100 }
101
102 inline byte ReadByte()
103 {
104 if (this->bufp == this->bufe) {
105 size_t len = this->reader->Read(this->buf, lengthof(this->buf));
106 if (len == 0) SlErrorCorrupt("Unexpected end of chunk");
107
108 this->read += len;
109 this->bufp = this->buf;
110 this->bufe = this->buf + len;
111 }
112
113 return *this->bufp++;
114 }
115
120 size_t GetSize() const
121 {
122 return this->read - (this->bufe - this->bufp);
123 }
124 };
125
126
128 struct MemoryDumper {
129 std::vector<byte *> blocks;
130 byte *buf;
131 byte *bufe;
132
134 MemoryDumper() : buf(nullptr), bufe(nullptr)
135 {
136 }
137
138 ~MemoryDumper()
139 {
140 for (auto p : this->blocks) {
141 free(p);
142 }
143 }
144
149 inline void WriteByte(byte b)
150 {
151 /* Are we at the end of this chunk? */
152 if (this->buf == this->bufe) {
153 this->buf = CallocT<byte>(MEMORY_CHUNK_SIZE);
154 this->blocks.push_back(this->buf);
155 this->bufe = this->buf + MEMORY_CHUNK_SIZE;
156 }
157
158 *this->buf++ = b;
159 }
160
165 void Flush(std::shared_ptr<SaveFilter> writer)
166 {
167 uint i = 0;
168 size_t t = this->GetSize();
169
170 while (t > 0) {
171 size_t to_write = std::min(MEMORY_CHUNK_SIZE, t);
172
173 writer->Write(this->blocks[i++], to_write);
174 t -= to_write;
175 }
176
177 writer->Finish();
178 }
179
184 size_t GetSize() const
185 {
186 return this->blocks.size() * MEMORY_CHUNK_SIZE - (this->bufe - this->buf);
187 }
188 };
189
191 struct SaveLoadParams {
192 SaveLoadAction action;
193 NeedLength need_length;
194 byte block_mode;
195 bool error;
196
197 size_t obj_len;
198 int array_index, last_array_index;
199 bool expect_table_header;
200
201 std::unique_ptr<MemoryDumper> dumper;
202 std::shared_ptr<SaveFilter> sf;
203
204 std::unique_ptr<ReadBuffer> reader;
205 std::shared_ptr<LoadFilter> lf;
206
207 StringID error_str;
208 std::string extra_msg;
209
210 bool saveinprogress;
211 };
212
213 static SaveLoadParams _sl;
214
215 static const std::vector<ChunkHandlerRef> &ChunkHandlers()
216 {
217 /* These define the chunks */
218 extern const ChunkHandlerTable _gamelog_chunk_handlers;
219 extern const ChunkHandlerTable _map_chunk_handlers;
220 extern const ChunkHandlerTable _misc_chunk_handlers;
221 extern const ChunkHandlerTable _name_chunk_handlers;
222 extern const ChunkHandlerTable _cheat_chunk_handlers;
223 extern const ChunkHandlerTable _setting_chunk_handlers;
224 extern const ChunkHandlerTable _company_chunk_handlers;
225 extern const ChunkHandlerTable _engine_chunk_handlers;
226 extern const ChunkHandlerTable _veh_chunk_handlers;
227 extern const ChunkHandlerTable _waypoint_chunk_handlers;
228 extern const ChunkHandlerTable _depot_chunk_handlers;
229 extern const ChunkHandlerTable _order_chunk_handlers;
230 extern const ChunkHandlerTable _town_chunk_handlers;
231 extern const ChunkHandlerTable _sign_chunk_handlers;
232 extern const ChunkHandlerTable _station_chunk_handlers;
233 extern const ChunkHandlerTable _industry_chunk_handlers;
234 extern const ChunkHandlerTable _economy_chunk_handlers;
235 extern const ChunkHandlerTable _subsidy_chunk_handlers;
236 extern const ChunkHandlerTable _cargomonitor_chunk_handlers;
237 extern const ChunkHandlerTable _goal_chunk_handlers;
238 extern const ChunkHandlerTable _story_page_chunk_handlers;
239 extern const ChunkHandlerTable _league_chunk_handlers;
240 extern const ChunkHandlerTable _ai_chunk_handlers;
241 extern const ChunkHandlerTable _game_chunk_handlers;
242 extern const ChunkHandlerTable _animated_tile_chunk_handlers;
243 extern const ChunkHandlerTable _newgrf_chunk_handlers;
244 extern const ChunkHandlerTable _group_chunk_handlers;
245 extern const ChunkHandlerTable _cargopacket_chunk_handlers;
246 extern const ChunkHandlerTable _autoreplace_chunk_handlers;
247 extern const ChunkHandlerTable _labelmaps_chunk_handlers;
248 extern const ChunkHandlerTable _linkgraph_chunk_handlers;
249 extern const ChunkHandlerTable _airport_chunk_handlers;
250 extern const ChunkHandlerTable _object_chunk_handlers;
251 extern const ChunkHandlerTable _persistent_storage_chunk_handlers;
252 extern const ChunkHandlerTable _water_region_chunk_handlers;
253 extern const ChunkHandlerTable _randomizer_chunk_handlers;
254
256 static const ChunkHandlerTable _chunk_handler_tables[] = {
257 _gamelog_chunk_handlers,
258 _map_chunk_handlers,
259 _misc_chunk_handlers,
260 _name_chunk_handlers,
261 _cheat_chunk_handlers,
262 _setting_chunk_handlers,
263 _veh_chunk_handlers,
264 _waypoint_chunk_handlers,
265 _depot_chunk_handlers,
266 _order_chunk_handlers,
267 _industry_chunk_handlers,
268 _economy_chunk_handlers,
269 _subsidy_chunk_handlers,
270 _cargomonitor_chunk_handlers,
271 _goal_chunk_handlers,
272 _story_page_chunk_handlers,
273 _league_chunk_handlers,
274 _engine_chunk_handlers,
275 _town_chunk_handlers,
276 _sign_chunk_handlers,
277 _station_chunk_handlers,
278 _company_chunk_handlers,
279 _ai_chunk_handlers,
280 _game_chunk_handlers,
281 _animated_tile_chunk_handlers,
282 _newgrf_chunk_handlers,
283 _group_chunk_handlers,
284 _cargopacket_chunk_handlers,
285 _autoreplace_chunk_handlers,
286 _labelmaps_chunk_handlers,
287 _linkgraph_chunk_handlers,
288 _airport_chunk_handlers,
289 _object_chunk_handlers,
290 _persistent_storage_chunk_handlers,
291 _water_region_chunk_handlers,
292 _randomizer_chunk_handlers,
293 };
294
295 static std::vector<ChunkHandlerRef> _chunk_handlers;
296
297 if (_chunk_handlers.empty()) {
298 for (auto &chunk_handler_table : _chunk_handler_tables) {
299 for (auto &chunk_handler : chunk_handler_table) {
300 _chunk_handlers.push_back(chunk_handler);
301 }
302 }
303 }
304
305 return _chunk_handlers;
306 }
307
309 static void SlNullPointers()
310 {
311 _sl.action = SLA_NULL;
312
313 /* We don't want any savegame conversion code to run
314 * during NULLing; especially those that try to get
315 * pointers from other pools. */
316 _sl_version = SAVEGAME_VERSION;
317
318 for (const ChunkHandler &ch : ChunkHandlers()) {
319 Debug(sl, 3, "Nulling pointers for {}", ch.GetName());
320 ch.FixPointers();
321 }
322
323 assert(_sl.action == SLA_NULL);
324 }
325
334 [[noreturn]] void SlError(StringID string, const std::string &extra_msg)
335 {
336 /* Distinguish between loading into _load_check_data vs. normal save/load. */
337 if (_sl.action == SLA_LOAD_CHECK) {
338 _load_check_data.error = string;
339 _load_check_data.error_msg = extra_msg;
340 } else {
341 _sl.error_str = string;
342 _sl.extra_msg = extra_msg;
343 }
344
345 /* We have to nullptr all pointers here; we might be in a state where
346 * the pointers are actually filled with indices, which means that
347 * when we access them during cleaning the pool dereferences of
348 * those indices will be made with segmentation faults as result. */
349 if (_sl.action == SLA_LOAD || _sl.action == SLA_PTRS) SlNullPointers();
350
351 /* Logging could be active. */
352 _gamelog.StopAnyAction();
353
354 throw std::exception();
355 }
356
364 [[noreturn]] void SlErrorCorrupt(const std::string &msg)
365 {
366 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, msg);
367 }
368
369
370 typedef void (*AsyncSaveFinishProc)();
371 static std::atomic<AsyncSaveFinishProc> _async_save_finish;
372 static std::thread _save_thread;
373
378 static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
379 {
380 if (_exit_game) return;
381 while (_async_save_finish.load(std::memory_order_acquire) != nullptr) CSleep(10);
382
383 _async_save_finish.store(proc, std::memory_order_release);
384 }
385
389 void ProcessAsyncSaveFinish()
390 {
391 AsyncSaveFinishProc proc = _async_save_finish.exchange(nullptr, std::memory_order_acq_rel);
392 if (proc == nullptr) return;
393
394 proc();
395
396 if (_save_thread.joinable()) {
397 _save_thread.join();
398 }
399 }
400
405 byte SlReadByte()
406 {
407 return _sl.reader->ReadByte();
408 }
409
414 void SlWriteByte(byte b)
415 {
416 _sl.dumper->WriteByte(b);
417 }
418
419 static inline int SlReadUint16()
420 {
421 int x = SlReadByte() << 8;
422 return x | SlReadByte();
423 }
424
425 static inline uint32_t SlReadUint32()
426 {
427 uint32_t x = SlReadUint16() << 16;
428 return x | SlReadUint16();
429 }
430
431 static inline uint64_t SlReadUint64()
432 {
433 uint32_t x = SlReadUint32();
434 uint32_t y = SlReadUint32();
435 return (uint64_t)x << 32 | y;
436 }
437
438 static inline void SlWriteUint16(uint16_t v)
439 {
440 SlWriteByte(GB(v, 8, 8));
441 SlWriteByte(GB(v, 0, 8));
442 }
443
444 static inline void SlWriteUint32(uint32_t v)
445 {
446 SlWriteUint16(GB(v, 16, 16));
447 SlWriteUint16(GB(v, 0, 16));
448 }
449
450 static inline void SlWriteUint64(uint64_t x)
451 {
452 SlWriteUint32((uint32_t)(x >> 32));
453 SlWriteUint32((uint32_t)x);
454 }
455
465 static uint SlReadSimpleGamma()
466 {
467 uint i = SlReadByte();
468 if (HasBit(i, 7)) {
469 i &= ~0x80;
470 if (HasBit(i, 6)) {
471 i &= ~0x40;
472 if (HasBit(i, 5)) {
473 i &= ~0x20;
474 if (HasBit(i, 4)) {
475 i &= ~0x10;
476 if (HasBit(i, 3)) {
477 SlErrorCorrupt("Unsupported gamma");
478 }
479 i = SlReadByte(); // 32 bits only.
480 }
481 i = (i << 8) | SlReadByte();
482 }
483 i = (i << 8) | SlReadByte();
484 }
485 i = (i << 8) | SlReadByte();
486 }
487 return i;
488 }
489
507 static void SlWriteSimpleGamma(size_t i)
508 {
509 if (i >= (1 << 7)) {
510 if (i >= (1 << 14)) {
511 if (i >= (1 << 21)) {
512 if (i >= (1 << 28)) {
513 assert(i <= UINT32_MAX); // We can only support 32 bits for now.
514 SlWriteByte((byte)(0xF0));
515 SlWriteByte((byte)(i >> 24));
516 } else {
517 SlWriteByte((byte)(0xE0 | (i >> 24)));
518 }
519 SlWriteByte((byte)(i >> 16));
520 } else {
521 SlWriteByte((byte)(0xC0 | (i >> 16)));
522 }
523 SlWriteByte((byte)(i >> 8));
524 } else {
525 SlWriteByte((byte)(0x80 | (i >> 8)));
526 }
527 }
528 SlWriteByte((byte)i);
529 }
530
532 static inline uint SlGetGammaLength(size_t i)
533 {
534 return 1 + (i >= (1 << 7)) + (i >= (1 << 14)) + (i >= (1 << 21)) + (i >= (1 << 28));
535 }
536
537 static inline uint SlReadSparseIndex()
538 {
539 return SlReadSimpleGamma();
540 }
541
542 static inline void SlWriteSparseIndex(uint index)
543 {
544 SlWriteSimpleGamma(index);
545 }
546
547 static inline uint SlReadArrayLength()
548 {
549 return SlReadSimpleGamma();
550 }
551
552 static inline void SlWriteArrayLength(size_t length)
553 {
554 SlWriteSimpleGamma(length);
555 }
556
557 static inline uint SlGetArrayLength(size_t length)
558 {
559 return SlGetGammaLength(length);
560 }
561
565 static uint8_t GetSavegameFileType(const SaveLoad &sld)
566 {
567 switch (sld.cmd) {
568 case SL_VAR:
569 return GetVarFileType(sld.conv); break;
570
571 case SL_STDSTR:
572 case SL_ARR:
573 case SL_VECTOR:
574 case SL_DEQUE:
575 return GetVarFileType(sld.conv) | SLE_FILE_HAS_LENGTH_FIELD; break;
576
577 case SL_REF:
578 return IsSavegameVersionBefore(SLV_69) ? SLE_FILE_U16 : SLE_FILE_U32;
579
580 case SL_REFLIST:
581 return (IsSavegameVersionBefore(SLV_69) ? SLE_FILE_U16 : SLE_FILE_U32) | SLE_FILE_HAS_LENGTH_FIELD;
582
583 case SL_SAVEBYTE:
584 return SLE_FILE_U8;
585
586 case SL_STRUCT:
587 case SL_STRUCTLIST:
588 return SLE_FILE_STRUCT | SLE_FILE_HAS_LENGTH_FIELD;
589
590 default: NOT_REACHED();
591 }
592 }
593
600 static inline uint SlCalcConvMemLen(VarType conv)
601 {
602 static const byte conv_mem_size[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
603
604 switch (GetVarMemType(conv)) {
605 case SLE_VAR_STR:
606 case SLE_VAR_STRQ:
607 return SlReadArrayLength();
608
609 default:
610 uint8_t type = GetVarMemType(conv) >> 4;
611 assert(type < lengthof(conv_mem_size));
612 return conv_mem_size[type];
613 }
614 }
615
622 static inline byte SlCalcConvFileLen(VarType conv)
623 {
624 static const byte conv_file_size[] = {0, 1, 1, 2, 2, 4, 4, 8, 8, 2};
625
626 switch (GetVarFileType(conv)) {
627 case SLE_FILE_STRING:
628 return SlReadArrayLength();
629
630 default:
631 uint8_t type = GetVarFileType(conv);
632 if (type >= lengthof(conv_file_size)) fmt::println("{}", type);
633 assert(type < lengthof(conv_file_size));
634 return conv_file_size[type];
635 }
636 }
637
639 static inline size_t SlCalcRefLen()
640 {
641 return IsSavegameVersionBefore(SLV_69) ? 2 : 4;
642 }
643
644 void SlSetArrayIndex(uint index)
645 {
646 _sl.need_length = NL_WANTLENGTH;
647 _sl.array_index = index;
648 }
649
650 static size_t _next_offs;
651
656 int SlIterateArray()
657 {
658 /* After reading in the whole array inside the loop
659 * we must have read in all the data, so we must be at end of current block. */
660 if (_next_offs != 0 && _sl.reader->GetSize() != _next_offs) {
661 SlErrorCorruptFmt("Invalid chunk size iterating array - expected to be at position {}, actually at {}", _next_offs, _sl.reader->GetSize());
662 }
663
664 for (;;) {
665 uint length = SlReadArrayLength();
666 if (length == 0) {
667 assert(!_sl.expect_table_header);
668 _next_offs = 0;
669 return -1;
670 }
671
672 _sl.obj_len = --length;
673 _next_offs = _sl.reader->GetSize() + length;
674
675 if (_sl.expect_table_header) {
676 _sl.expect_table_header = false;
677 return INT32_MAX;
678 }
679
680 int index;
681 switch (_sl.block_mode) {
682 case CH_SPARSE_TABLE:
683 case CH_SPARSE_ARRAY: index = (int)SlReadSparseIndex(); break;
684 case CH_TABLE:
685 case CH_ARRAY: index = _sl.array_index++; break;
686 default:
687 Debug(sl, 0, "SlIterateArray error");
688 return -1; // error
689 }
690
691 if (length != 0) return index;
692 }
693 }
694
698 void SlSkipArray()
699 {
700 while (SlIterateArray() != -1) {
701 SlSkipBytes(_next_offs - _sl.reader->GetSize());
702 }
703 }
704
710 void SlSetLength(size_t length)
711 {
712 assert(_sl.action == SLA_SAVE);
713
714 switch (_sl.need_length) {
715 case NL_WANTLENGTH:
716 _sl.need_length = NL_NONE;
717 if ((_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE) && _sl.expect_table_header) {
718 _sl.expect_table_header = false;
719 SlWriteArrayLength(length + 1);
720 break;
721 }
722
723 switch (_sl.block_mode) {
724 case CH_RIFF:
725 /* Ugly encoding of >16M RIFF chunks
726 * The lower 24 bits are normal
727 * The uppermost 4 bits are bits 24:27 */
728 assert(length < (1 << 28));
729 SlWriteUint32((uint32_t)((length & 0xFFFFFF) | ((length >> 24) << 28)));
730 break;
731 case CH_TABLE:
732 case CH_ARRAY:
733 assert(_sl.last_array_index <= _sl.array_index);
734 while (++_sl.last_array_index <= _sl.array_index) {
735 SlWriteArrayLength(1);
736 }
737 SlWriteArrayLength(length + 1);
738 break;
739 case CH_SPARSE_TABLE:
740 case CH_SPARSE_ARRAY:
741 SlWriteArrayLength(length + 1 + SlGetArrayLength(_sl.array_index)); // Also include length of sparse index.
742 SlWriteSparseIndex(_sl.array_index);
743 break;
744 default: NOT_REACHED();
745 }
746 break;
747
748 case NL_CALCLENGTH:
749 _sl.obj_len += (int)length;
750 break;
751
752 default: NOT_REACHED();
753 }
754 }
755
762 static void SlCopyBytes(void *ptr, size_t length)
763 {
764 byte *p = (byte *)ptr;
765
766 switch (_sl.action) {
767 case SLA_LOAD_CHECK:
768 case SLA_LOAD:
769 for (; length != 0; length--) *p++ = SlReadByte();
770 break;
771 case SLA_SAVE:
772 for (; length != 0; length--) SlWriteByte(*p++);
773 break;
774 default: NOT_REACHED();
775 }
776 }
777
779 size_t SlGetFieldLength()
780 {
781 return _sl.obj_len;
782 }
783
791 int64_t ReadValue(const void *ptr, VarType conv)
792 {
793 switch (GetVarMemType(conv)) {
794 case SLE_VAR_BL: return (*(const bool *)ptr != 0);
795 case SLE_VAR_I8: return *(const int8_t *)ptr;
796 case SLE_VAR_U8: return *(const byte *)ptr;
797 case SLE_VAR_I16: return *(const int16_t *)ptr;
798 case SLE_VAR_U16: return *(const uint16_t*)ptr;
799 case SLE_VAR_I32: return *(const int32_t *)ptr;
800 case SLE_VAR_U32: return *(const uint32_t*)ptr;
801 case SLE_VAR_I64: return *(const int64_t *)ptr;
802 case SLE_VAR_U64: return *(const uint64_t*)ptr;
803 case SLE_VAR_NULL:return 0;
804 default: NOT_REACHED();
805 }
806 }
807
815 void WriteValue(void *ptr, VarType conv, int64_t val)
816 {
817 switch (GetVarMemType(conv)) {
818 case SLE_VAR_BL: *(bool *)ptr = (val != 0); break;
819 case SLE_VAR_I8: *(int8_t *)ptr = val; break;
820 case SLE_VAR_U8: *(byte *)ptr = val; break;
821 case SLE_VAR_I16: *(int16_t *)ptr = val; break;
822 case SLE_VAR_U16: *(uint16_t*)ptr = val; break;
823 case SLE_VAR_I32: *(int32_t *)ptr = val; break;
824 case SLE_VAR_U32: *(uint32_t*)ptr = val; break;
825 case SLE_VAR_I64: *(int64_t *)ptr = val; break;
826 case SLE_VAR_U64: *(uint64_t*)ptr = val; break;
827 case SLE_VAR_NAME: *reinterpret_cast<std::string *>(ptr) = CopyFromOldName(val); break;
828 case SLE_VAR_NULL: break;
829 default: NOT_REACHED();
830 }
831 }
832
841 static void SlSaveLoadConv(void *ptr, VarType conv)
842 {
843 switch (_sl.action) {
844 case SLA_SAVE: {
845 int64_t x = ReadValue(ptr, conv);
846
847 /* Write the value to the file and check if its value is in the desired range */
848 switch (GetVarFileType(conv)) {
849 case SLE_FILE_I8: assert(x >= -128 && x <= 127); SlWriteByte(x);break;
850 case SLE_FILE_U8: assert(x >= 0 && x <= 255); SlWriteByte(x);break;
851 case SLE_FILE_I16:assert(x >= -32768 && x <= 32767); SlWriteUint16(x);break;
852 case SLE_FILE_STRINGID:
853 case SLE_FILE_U16:assert(x >= 0 && x <= 65535); SlWriteUint16(x);break;
854 case SLE_FILE_I32:
855 case SLE_FILE_U32: SlWriteUint32((uint32_t)x);break;
856 case SLE_FILE_I64:
857 case SLE_FILE_U64: SlWriteUint64(x);break;
858 default: NOT_REACHED();
859 }
860 break;
861 }
862 case SLA_LOAD_CHECK:
863 case SLA_LOAD: {
864 int64_t x;
865 /* Read a value from the file */
866 switch (GetVarFileType(conv)) {
867 case SLE_FILE_I8: x = (int8_t )SlReadByte(); break;
868 case SLE_FILE_U8: x = (byte )SlReadByte(); break;
869 case SLE_FILE_I16: x = (int16_t )SlReadUint16(); break;
870 case SLE_FILE_U16: x = (uint16_t)SlReadUint16(); break;
871 case SLE_FILE_I32: x = (int32_t )SlReadUint32(); break;
872 case SLE_FILE_U32: x = (uint32_t)SlReadUint32(); break;
873 case SLE_FILE_I64: x = (int64_t )SlReadUint64(); break;
874 case SLE_FILE_U64: x = (uint64_t)SlReadUint64(); break;
875 case SLE_FILE_STRINGID: x = RemapOldStringID((uint16_t)SlReadUint16()); break;
876 default: NOT_REACHED();
877 }
878
879 /* Write The value to the struct. These ARE endian safe. */
880 WriteValue(ptr, conv, x);
881 break;
882 }
883 case SLA_PTRS: break;
884 case SLA_NULL: break;
885 default: NOT_REACHED();
886 }
887 }
888
896 static inline size_t SlCalcStdStringLen(const void *ptr)
897 {
898 const std::string *str = reinterpret_cast<const std::string *>(ptr);
899
900 size_t len = str->length();
901 return len + SlGetArrayLength(len); // also include the length of the index
902 }
903
904
912 static void FixSCCEncoded(std::string &str)
913 {
914 for (size_t i = 0; i < str.size(); /* nothing. */) {
915 size_t len = Utf8EncodedCharLen(str[i]);
916 if (len == 0 || i + len > str.size()) break;
917
918 char32_t c;
919 Utf8Decode(&c, &str[i]);
920 if (c == 0xE028 || c == 0xE02A) Utf8Encode(&str[i], SCC_ENCODED);
921 i += len;
922 }
923 }
924
930 static void SlStdString(void *ptr, VarType conv)
931 {
932 std::string *str = reinterpret_cast<std::string *>(ptr);
933
934 switch (_sl.action) {
935 case SLA_SAVE: {
936 size_t len = str->length();
937 SlWriteArrayLength(len);
938 SlCopyBytes(const_cast<void *>(static_cast<const void *>(str->c_str())), len);
939 break;
940 }
941
942 case SLA_LOAD_CHECK:
943 case SLA_LOAD: {
944 size_t len = SlReadArrayLength();
945 if (GetVarMemType(conv) == SLE_VAR_NULL) {
946 SlSkipBytes(len);
947 return;
948 }
949
950 str->resize(len);
951 SlCopyBytes(str->data(), len);
952
953 StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK;
954 if ((conv & SLF_ALLOW_CONTROL) != 0) {
955 settings = settings | SVS_ALLOW_CONTROL_CODE;
956 if (IsSavegameVersionBefore(SLV_169)) FixSCCEncoded(*str);
957 }
958 if ((conv & SLF_ALLOW_NEWLINE) != 0) {
959 settings = settings | SVS_ALLOW_NEWLINE;
960 }
961 *str = StrMakeValid(*str, settings);
962 }
963
964 case SLA_PTRS: break;
965 case SLA_NULL: break;
966 default: NOT_REACHED();
967 }
968 }
969
978 static void SlCopyInternal(void *object, size_t length, VarType conv)
979 {
980 if (GetVarMemType(conv) == SLE_VAR_NULL) {
981 assert(_sl.action != SLA_SAVE); // Use SL_NULL if you want to write null-bytes
982 SlSkipBytes(length * SlCalcConvFileLen(conv));
983 return;
984 }
985
986 /* NOTICE - handle some buggy stuff, in really old versions everything was saved
987 * as a byte-type. So detect this, and adjust object size accordingly */
988 if (_sl.action != SLA_SAVE && _sl_version == 0) {
989 /* all objects except difficulty settings */
990 if (conv == SLE_INT16 || conv == SLE_UINT16 || conv == SLE_STRINGID ||
991 conv == SLE_INT32 || conv == SLE_UINT32) {
992 SlCopyBytes(object, length * SlCalcConvFileLen(conv));
993 return;
994 }
995 /* used for conversion of Money 32bit->64bit */
996 if (conv == (SLE_FILE_I32 | SLE_VAR_I64)) {
997 for (uint i = 0; i < length; i++) {
998 ((int64_t*)object)[i] = (int32_t)BSWAP32(SlReadUint32());
999 }
1000 return;
1001 }
1002 }
1003
1004 /* If the size of elements is 1 byte both in file and memory, no special
1005 * conversion is needed, use specialized copy-copy function to speed up things */
1006 if (conv == SLE_INT8 || conv == SLE_UINT8) {
1007 SlCopyBytes(object, length);
1008 } else {
1009 byte *a = (byte*)object;
1010 byte mem_size = SlCalcConvMemLen(conv);
1011
1012 for (; length != 0; length --) {
1013 SlSaveLoadConv(a, conv);
1014 a += mem_size; // get size
1015 }
1016 }
1017 }
1018
1027 void SlCopy(void *object, size_t length, VarType conv)
1028 {
1029 if (_sl.action == SLA_PTRS || _sl.action == SLA_NULL) return;
1030
1031 /* Automatically calculate the length? */
1032 if (_sl.need_length != NL_NONE) {
1033 SlSetLength(length * SlCalcConvFileLen(conv));
1034 /* Determine length only? */
1035 if (_sl.need_length == NL_CALCLENGTH) return;
1036 }
1037
1038 SlCopyInternal(object, length, conv);
1039 }
1040
1046 static inline size_t SlCalcArrayLen(size_t length, VarType conv)
1047 {
1048 return SlCalcConvFileLen(conv) * length + SlGetArrayLength(length);
1049 }
1050
1057 static void SlArray(void *array, size_t length, VarType conv)
1058 {
1059 switch (_sl.action) {
1060 case SLA_SAVE:
1061 SlWriteArrayLength(length);
1062 SlCopyInternal(array, length, conv);
1063 return;
1064
1065 case SLA_LOAD_CHECK:
1066 case SLA_LOAD: {
1067 if (!IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH)) {
1068 size_t sv_length = SlReadArrayLength();
1069 if (GetVarMemType(conv) == SLE_VAR_NULL) {
1070 /* We don't know this field, so we assume the length in the savegame is correct. */
1071 length = sv_length;
1072 } else if (sv_length != length) {
1073 /* If the SLE_ARR changes size, a savegame bump is required
1074 * and the developer should have written conversion lines.
1075 * Error out to make this more visible. */
1076 SlErrorCorrupt("Fixed-length array is of wrong length");
1077 }
1078 }
1079
1080 SlCopyInternal(array, length, conv);
1081 return;
1082 }
1083
1084 case SLA_PTRS:
1085 case SLA_NULL:
1086 return;
1087
1088 default:
1089 NOT_REACHED();
1090 }
1091 }
1092
1103 static size_t ReferenceToInt(const void *obj, SLRefType rt)
1104 {
1105 assert(_sl.action == SLA_SAVE);
1106
1107 if (obj == nullptr) return 0;
1108
1109 switch (rt) {
1110 case REF_VEHICLE_OLD: // Old vehicles we save as new ones
1111 case REF_VEHICLE: return ((const Vehicle*)obj)->index + 1;
1112 case REF_STATION: return ((const Station*)obj)->index + 1;
1113 case REF_TOWN: return ((const Town*)obj)->index + 1;
1114 case REF_ORDER: return ((const Order*)obj)->index + 1;
1115 case REF_ROADSTOPS: return ((const RoadStop*)obj)->index + 1;
1116 case REF_ENGINE_RENEWS: return ((const EngineRenew*)obj)->index + 1;
1117 case REF_CARGO_PACKET: return ((const CargoPacket*)obj)->index + 1;
1118 case REF_ORDERLIST: return ((const OrderList*)obj)->index + 1;
1119 case REF_STORAGE: return ((const PersistentStorage*)obj)->index + 1;
1120 case REF_LINK_GRAPH: return ((const LinkGraph*)obj)->index + 1;
1121 case REF_LINK_GRAPH_JOB: return ((const LinkGraphJob*)obj)->index + 1;
1122 default: NOT_REACHED();
1123 }
1124 }
1125
1136 static void *IntToReference(size_t index, SLRefType rt)
1137 {
1138 static_assert(sizeof(size_t) <= sizeof(void *));
1139
1140 assert(_sl.action == SLA_PTRS);
1141
1142 /* After version 4.3 REF_VEHICLE_OLD is saved as REF_VEHICLE,
1143 * and should be loaded like that */
1144 if (rt == REF_VEHICLE_OLD && !IsSavegameVersionBefore(SLV_4, 4)) {
1145 rt = REF_VEHICLE;
1146 }
1147
1148 /* No need to look up nullptr pointers, just return immediately */
1149 if (index == (rt == REF_VEHICLE_OLD ? 0xFFFF : 0)) return nullptr;
1150
1151 /* Correct index. Old vehicles were saved differently:
1152 * invalid vehicle was 0xFFFF, now we use 0x0000 for everything invalid. */
1153 if (rt != REF_VEHICLE_OLD) index--;
1154
1155 switch (rt) {
1156 case REF_ORDERLIST:
1157 if (OrderList::IsValidID(index)) return OrderList::Get(index);
1158 SlErrorCorrupt("Referencing invalid OrderList");
1159
1160 case REF_ORDER:
1161 if (Order::IsValidID(index)) return Order::Get(index);
1162 /* in old versions, invalid order was used to mark end of order list */
1163 if (IsSavegameVersionBefore(SLV_5, 2)) return nullptr;
1164 SlErrorCorrupt("Referencing invalid Order");
1165
1166 case REF_VEHICLE_OLD:
1167 case REF_VEHICLE:
1168 if (Vehicle::IsValidID(index)) return Vehicle::Get(index);
1169 SlErrorCorrupt("Referencing invalid Vehicle");
1170
1171 case REF_STATION:
1172 if (Station::IsValidID(index)) return Station::Get(index);
1173 SlErrorCorrupt("Referencing invalid Station");
1174
1175 case REF_TOWN:
1176 if (Town::IsValidID(index)) return Town::Get(index);
1177 SlErrorCorrupt("Referencing invalid Town");
1178
1179 case REF_ROADSTOPS:
1180 if (RoadStop::IsValidID(index)) return RoadStop::Get(index);
1181 SlErrorCorrupt("Referencing invalid RoadStop");
1182
1183 case REF_ENGINE_RENEWS:
1184 if (EngineRenew::IsValidID(index)) return EngineRenew::Get(index);
1185 SlErrorCorrupt("Referencing invalid EngineRenew");
1186
1187 case REF_CARGO_PACKET:
1188 if (CargoPacket::IsValidID(index)) return CargoPacket::Get(index);
1189 SlErrorCorrupt("Referencing invalid CargoPacket");
1190
1191 case REF_STORAGE:
1192 if (PersistentStorage::IsValidID(index)) return PersistentStorage::Get(index);
1193 SlErrorCorrupt("Referencing invalid PersistentStorage");
1194
1195 case REF_LINK_GRAPH:
1196 if (LinkGraph::IsValidID(index)) return LinkGraph::Get(index);
1197 SlErrorCorrupt("Referencing invalid LinkGraph");
1198
1199 case REF_LINK_GRAPH_JOB:
1200 if (LinkGraphJob::IsValidID(index)) return LinkGraphJob::Get(index);
1201 SlErrorCorrupt("Referencing invalid LinkGraphJob");
1202
1203 default: NOT_REACHED();
1204 }
1205 }
1206
1212 void SlSaveLoadRef(void *ptr, VarType conv)
1213 {
1214 switch (_sl.action) {
1215 case SLA_SAVE:
1216 SlWriteUint32((uint32_t)ReferenceToInt(*(void **)ptr, (SLRefType)conv));
1217 break;
1218 case SLA_LOAD_CHECK:
1219 case SLA_LOAD:
1220 *(size_t *)ptr = IsSavegameVersionBefore(SLV_69) ? SlReadUint16() : SlReadUint32();
1221 break;
1222 case SLA_PTRS:
1223 *(void **)ptr = IntToReference(*(size_t *)ptr, (SLRefType)conv);
1224 break;
1225 case SLA_NULL:
1226 *(void **)ptr = nullptr;
1227 break;
1228 default: NOT_REACHED();
1229 }
1230 }
1231
1235 template <template<typename, typename> typename Tstorage, typename Tvar, typename Tallocator = std::allocator<Tvar>>
1236 class SlStorageHelper {
1237 typedef Tstorage<Tvar, Tallocator> SlStorageT;
1238 public:
1245 static size_t SlCalcLen(const void *storage, VarType conv, SaveLoadType cmd = SL_VAR)
1246 {
1247 assert(cmd == SL_VAR || cmd == SL_REF);
1248
1249 const SlStorageT *list = static_cast<const SlStorageT *>(storage);
1250
1251 int type_size = SlGetArrayLength(list->size());
1252 int item_size = SlCalcConvFileLen(cmd == SL_VAR ? conv : (VarType)SLE_FILE_U32);
1253 return list->size() * item_size + type_size;
1254 }
1255
1256 static void SlSaveLoadMember(SaveLoadType cmd, Tvar *item, VarType conv)
1257 {
1258 switch (cmd) {
1259 case SL_VAR: SlSaveLoadConv(item, conv); break;
1260 case SL_REF: SlSaveLoadRef(item, conv); break;
1261 default:
1262 NOT_REACHED();
1263 }
1264 }
1265
1272 static void SlSaveLoad(void *storage, VarType conv, SaveLoadType cmd = SL_VAR)
1273 {
1274 assert(cmd == SL_VAR || cmd == SL_REF);
1275
1276 SlStorageT *list = static_cast<SlStorageT *>(storage);
1277
1278 switch (_sl.action) {
1279 case SLA_SAVE:
1280 SlWriteArrayLength(list->size());
1281
1282 for (auto &item : *list) {
1283 SlSaveLoadMember(cmd, &item, conv);
1284 }
1285 break;
1286
1287 case SLA_LOAD_CHECK:
1288 case SLA_LOAD: {
1289 size_t length;
1290 switch (cmd) {
1291 case SL_VAR: length = IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? SlReadUint32() : SlReadArrayLength(); break;
1292 case SL_REF: length = IsSavegameVersionBefore(SLV_69) ? SlReadUint16() : IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? SlReadUint32() : SlReadArrayLength(); break;
1293 default: NOT_REACHED();
1294 }
1295
1296 /* Load each value and push to the end of the storage. */
1297 for (size_t i = 0; i < length; i++) {
1298 Tvar &data = list->emplace_back();
1299 SlSaveLoadMember(cmd, &data, conv);
1300 }
1301 break;
1302 }
1303
1304 case SLA_PTRS:
1305 for (auto &item : *list) {
1306 SlSaveLoadMember(cmd, &item, conv);
1307 }
1308 break;
1309
1310 case SLA_NULL:
1311 list->clear();
1312 break;
1313
1314 default: NOT_REACHED();
1315 }
1316 }
1317 };
1318
1324 static inline size_t SlCalcRefListLen(const void *list, VarType conv)
1325 {
1326 return SlStorageHelper<std::list, void *>::SlCalcLen(list, conv, SL_REF);
1327 }
1328
1334 static void SlRefList(void *list, VarType conv)
1335 {
1336 /* Automatically calculate the length? */
1337 if (_sl.need_length != NL_NONE) {
1338 SlSetLength(SlCalcRefListLen(list, conv));
1339 /* Determine length only? */
1340 if (_sl.need_length == NL_CALCLENGTH) return;
1341 }
1342
1343 SlStorageHelper<std::list, void *>::SlSaveLoad(list, conv, SL_REF);
1344 }
1345
1351 static inline size_t SlCalcDequeLen(const void *deque, VarType conv)
1352 {
1353 switch (GetVarMemType(conv)) {
1354 case SLE_VAR_BL: return SlStorageHelper<std::deque, bool>::SlCalcLen(deque, conv);
1355 case SLE_VAR_I8: return SlStorageHelper<std::deque, int8_t>::SlCalcLen(deque, conv);
1356 case SLE_VAR_U8: return SlStorageHelper<std::deque, uint8_t>::SlCalcLen(deque, conv);
1357 case SLE_VAR_I16: return SlStorageHelper<std::deque, int16_t>::SlCalcLen(deque, conv);
1358 case SLE_VAR_U16: return SlStorageHelper<std::deque, uint16_t>::SlCalcLen(deque, conv);
1359 case SLE_VAR_I32: return SlStorageHelper<std::deque, int32_t>::SlCalcLen(deque, conv);
1360 case SLE_VAR_U32: return SlStorageHelper<std::deque, uint32_t>::SlCalcLen(deque, conv);
1361 case SLE_VAR_I64: return SlStorageHelper<std::deque, int64_t>::SlCalcLen(deque, conv);
1362 case SLE_VAR_U64: return SlStorageHelper<std::deque, uint64_t>::SlCalcLen(deque, conv);
1363 default: NOT_REACHED();
1364 }
1365 }
1366
1372 static void SlDeque(void *deque, VarType conv)
1373 {
1374 switch (GetVarMemType(conv)) {
1375 case SLE_VAR_BL: SlStorageHelper<std::deque, bool>::SlSaveLoad(deque, conv); break;
1376 case SLE_VAR_I8: SlStorageHelper<std::deque, int8_t>::SlSaveLoad(deque, conv); break;
1377 case SLE_VAR_U8: SlStorageHelper<std::deque, uint8_t>::SlSaveLoad(deque, conv); break;
1378 case SLE_VAR_I16: SlStorageHelper<std::deque, int16_t>::SlSaveLoad(deque, conv); break;
1379 case SLE_VAR_U16: SlStorageHelper<std::deque, uint16_t>::SlSaveLoad(deque, conv); break;
1380 case SLE_VAR_I32: SlStorageHelper<std::deque, int32_t>::SlSaveLoad(deque, conv); break;
1381 case SLE_VAR_U32: SlStorageHelper<std::deque, uint32_t>::SlSaveLoad(deque, conv); break;
1382 case SLE_VAR_I64: SlStorageHelper<std::deque, int64_t>::SlSaveLoad(deque, conv); break;
1383 case SLE_VAR_U64: SlStorageHelper<std::deque, uint64_t>::SlSaveLoad(deque, conv); break;
1384 default: NOT_REACHED();
1385 }
1386 }
1387
1393 static inline size_t SlCalcVectorLen(const void *vector, VarType conv)
1394 {
1395 switch (GetVarMemType(conv)) {
1396 case SLE_VAR_BL: NOT_REACHED(); // Not supported
1397 case SLE_VAR_I8: return SlStorageHelper<std::vector, int8_t>::SlCalcLen(vector, conv);
1398 case SLE_VAR_U8: return SlStorageHelper<std::vector, uint8_t>::SlCalcLen(vector, conv);
1399 case SLE_VAR_I16: return SlStorageHelper<std::vector, int16_t>::SlCalcLen(vector, conv);
1400 case SLE_VAR_U16: return SlStorageHelper<std::vector, uint16_t>::SlCalcLen(vector, conv);
1401 case SLE_VAR_I32: return SlStorageHelper<std::vector, int32_t>::SlCalcLen(vector, conv);
1402 case SLE_VAR_U32: return SlStorageHelper<std::vector, uint32_t>::SlCalcLen(vector, conv);
1403 case SLE_VAR_I64: return SlStorageHelper<std::vector, int64_t>::SlCalcLen(vector, conv);
1404 case SLE_VAR_U64: return SlStorageHelper<std::vector, uint64_t>::SlCalcLen(vector, conv);
1405 default: NOT_REACHED();
1406 }
1407 }
1408
1414 static void SlVector(void *vector, VarType conv)
1415 {
1416 switch (GetVarMemType(conv)) {
1417 case SLE_VAR_BL: NOT_REACHED(); // Not supported
1418 case SLE_VAR_I8: SlStorageHelper<std::vector, int8_t>::SlSaveLoad(vector, conv); break;
1419 case SLE_VAR_U8: SlStorageHelper<std::vector, uint8_t>::SlSaveLoad(vector, conv); break;
1420 case SLE_VAR_I16: SlStorageHelper<std::vector, int16_t>::SlSaveLoad(vector, conv); break;
1421 case SLE_VAR_U16: SlStorageHelper<std::vector, uint16_t>::SlSaveLoad(vector, conv); break;
1422 case SLE_VAR_I32: SlStorageHelper<std::vector, int32_t>::SlSaveLoad(vector, conv); break;
1423 case SLE_VAR_U32: SlStorageHelper<std::vector, uint32_t>::SlSaveLoad(vector, conv); break;
1424 case SLE_VAR_I64: SlStorageHelper<std::vector, int64_t>::SlSaveLoad(vector, conv); break;
1425 case SLE_VAR_U64: SlStorageHelper<std::vector, uint64_t>::SlSaveLoad(vector, conv); break;
1426 default: NOT_REACHED();
1427 }
1428 }
1429
1431 static inline bool SlIsObjectValidInSavegame(const SaveLoad &sld)
1432 {
1433 return (_sl_version >= sld.version_from && _sl_version < sld.version_to);
1434 }
1435
1441 static size_t SlCalcTableHeader(const SaveLoadTable &slt)
1442 {
1443 size_t length = 0;
1444
1445 for (auto &sld : slt) {
1446 if (!SlIsObjectValidInSavegame(sld)) continue;
1447
1448 length += SlCalcConvFileLen(SLE_UINT8);
1449 length += SlCalcStdStringLen(&sld.name);
1450 }
1451
1452 length += SlCalcConvFileLen(SLE_UINT8); // End-of-list entry.
1453
1454 for (auto &sld : slt) {
1455 if (!SlIsObjectValidInSavegame(sld)) continue;
1456 if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1457 length += SlCalcTableHeader(sld.handler->GetDescription());
1458 }
1459 }
1460
1461 return length;
1462 }
1463
1470 size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt)
1471 {
1472 size_t length = 0;
1473
1474 /* Need to determine the length and write a length tag. */
1475 for (auto &sld : slt) {
1476 length += SlCalcObjMemberLength(object, sld);
1477 }
1478 return length;
1479 }
1480
1481 size_t SlCalcObjMemberLength(const void *object, const SaveLoad &sld)
1482 {
1483 assert(_sl.action == SLA_SAVE);
1484
1485 if (!SlIsObjectValidInSavegame(sld)) return 0;
1486
1487 switch (sld.cmd) {
1488 case SL_VAR: return SlCalcConvFileLen(sld.conv);
1489 case SL_REF: return SlCalcRefLen();
1490 case SL_ARR: return SlCalcArrayLen(sld.length, sld.conv);
1491 case SL_REFLIST: return SlCalcRefListLen(GetVariableAddress(object, sld), sld.conv);
1492 case SL_DEQUE: return SlCalcDequeLen(GetVariableAddress(object, sld), sld.conv);
1493 case SL_VECTOR: return SlCalcVectorLen(GetVariableAddress(object, sld), sld.conv);
1494 case SL_STDSTR: return SlCalcStdStringLen(GetVariableAddress(object, sld));
1495 case SL_SAVEBYTE: return 1; // a byte is logically of size 1
1496 case SL_NULL: return SlCalcConvFileLen(sld.conv) * sld.length;
1497
1498 case SL_STRUCT:
1499 case SL_STRUCTLIST: {
1500 NeedLength old_need_length = _sl.need_length;
1501 size_t old_obj_len = _sl.obj_len;
1502
1503 _sl.need_length = NL_CALCLENGTH;
1504 _sl.obj_len = 0;
1505
1506 /* Pretend that we are saving to collect the object size. Other
1507 * means are difficult, as we don't know the length of the list we
1508 * are about to store. */
1509 sld.handler->Save(const_cast<void *>(object));
1510 size_t length = _sl.obj_len;
1511
1512 _sl.obj_len = old_obj_len;
1513 _sl.need_length = old_need_length;
1514
1515 if (sld.cmd == SL_STRUCT) {
1516 length += SlGetArrayLength(1);
1517 }
1518
1519 return length;
1520 }
1521
1522 default: NOT_REACHED();
1523 }
1524 return 0;
1525 }
1526
1527 static bool SlObjectMember(void *object, const SaveLoad &sld)
1528 {
1529 if (!SlIsObjectValidInSavegame(sld)) return false;
1530
1531 VarType conv = GB(sld.conv, 0, 8);
1532 switch (sld.cmd) {
1533 case SL_VAR:
1534 case SL_REF:
1535 case SL_ARR:
1536 case SL_REFLIST:
1537 case SL_DEQUE:
1538 case SL_VECTOR:
1539 case SL_STDSTR: {
1540 void *ptr = GetVariableAddress(object, sld);
1541
1542 switch (sld.cmd) {
1543 case SL_VAR: SlSaveLoadConv(ptr, conv); break;
1544 case SL_REF: SlSaveLoadRef(ptr, conv); break;
1545 case SL_ARR: SlArray(ptr, sld.length, conv); break;
1546 case SL_REFLIST: SlRefList(ptr, conv); break;
1547 case SL_DEQUE: SlDeque(ptr, conv); break;
1548 case SL_VECTOR: SlVector(ptr, conv); break;
1549 case SL_STDSTR: SlStdString(ptr, sld.conv); break;
1550 default: NOT_REACHED();
1551 }
1552 break;
1553 }
1554
1555 /* SL_SAVEBYTE writes a value to the savegame to identify the type of an object.
1556 * When loading, the value is read explicitly with SlReadByte() to determine which
1557 * object description to use. */
1558 case SL_SAVEBYTE: {
1559 void *ptr = GetVariableAddress(object, sld);
1560
1561 switch (_sl.action) {
1562 case SLA_SAVE: SlWriteByte(*(uint8_t *)ptr); break;
1563 case SLA_LOAD_CHECK:
1564 case SLA_LOAD:
1565 case SLA_PTRS:
1566 case SLA_NULL: break;
1567 default: NOT_REACHED();
1568 }
1569 break;
1570 }
1571
1572 case SL_NULL: {
1573 assert(GetVarMemType(sld.conv) == SLE_VAR_NULL);
1574
1575 switch (_sl.action) {
1576 case SLA_LOAD_CHECK:
1577 case SLA_LOAD: SlSkipBytes(SlCalcConvFileLen(sld.conv) * sld.length); break;
1578 case SLA_SAVE: for (int i = 0; i < SlCalcConvFileLen(sld.conv) * sld.length; i++) SlWriteByte(0); break;
1579 case SLA_PTRS:
1580 case SLA_NULL: break;
1581 default: NOT_REACHED();
1582 }
1583 break;
1584 }
1585
1586 case SL_STRUCT:
1587 case SL_STRUCTLIST:
1588 switch (_sl.action) {
1589 case SLA_SAVE: {
1590 if (sld.cmd == SL_STRUCT) {
1591 /* Store in the savegame if this struct was written or not. */
1592 SlSetStructListLength(SlCalcObjMemberLength(object, sld) > SlGetArrayLength(1) ? 1 : 0);
1593 }
1594 sld.handler->Save(object);
1595 break;
1596 }
1597
1598 case SLA_LOAD_CHECK: {
1599 if (sld.cmd == SL_STRUCT && !IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH)) {
1600 SlGetStructListLength(1);
1601 }
1602 sld.handler->LoadCheck(object);
1603 break;
1604 }
1605
1606 case SLA_LOAD: {
1607 if (sld.cmd == SL_STRUCT && !IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH)) {
1608 SlGetStructListLength(1);
1609 }
1610 sld.handler->Load(object);
1611 break;
1612 }
1613
1614 case SLA_PTRS:
1615 sld.handler->FixPointers(object);
1616 break;
1617
1618 case SLA_NULL: break;
1619 default: NOT_REACHED();
1620 }
1621 break;
1622
1623 default: NOT_REACHED();
1624 }
1625 return true;
1626 }
1627
1632 void SlSetStructListLength(size_t length)
1633 {
1634 /* Automatically calculate the length? */
1635 if (_sl.need_length != NL_NONE) {
1636 SlSetLength(SlGetArrayLength(length));
1637 if (_sl.need_length == NL_CALCLENGTH) return;
1638 }
1639
1640 SlWriteArrayLength(length);
1641 }
1642
1648 size_t SlGetStructListLength(size_t limit)
1649 {
1650 size_t length = SlReadArrayLength();
1651 if (length > limit) SlErrorCorrupt("List exceeds storage size");
1652
1653 return length;
1654 }
1655
1661 void SlObject(void *object, const SaveLoadTable &slt)
1662 {
1663 /* Automatically calculate the length? */
1664 if (_sl.need_length != NL_NONE) {
1665 SlSetLength(SlCalcObjLength(object, slt));
1666 if (_sl.need_length == NL_CALCLENGTH) return;
1667 }
1668
1669 for (auto &sld : slt) {
1670 SlObjectMember(object, sld);
1671 }
1672 }
1673
1678 class SlSkipHandler : public SaveLoadHandler {
1679 void Save(void *) const override
1680 {
1681 NOT_REACHED();
1682 }
1683
1684 void Load(void *object) const override
1685 {
1686 size_t length = SlGetStructListLength(UINT32_MAX);
1687 for (; length > 0; length--) {
1688 SlObject(object, this->GetLoadDescription());
1689 }
1690 }
1691
1692 void LoadCheck(void *object) const override
1693 {
1694 this->Load(object);
1695 }
1696
1697 virtual SaveLoadTable GetDescription() const override
1698 {
1699 return {};
1700 }
1701
1702 virtual SaveLoadCompatTable GetCompatDescription() const override
1703 {
1704 NOT_REACHED();
1705 }
1706 };
1707
1714 std::vector<SaveLoad> SlTableHeader(const SaveLoadTable &slt)
1715 {
1716 /* You can only use SlTableHeader if you are a CH_TABLE. */
1717 assert(_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
1718
1719 switch (_sl.action) {
1720 case SLA_LOAD_CHECK:
1721 case SLA_LOAD: {
1722 std::vector<SaveLoad> saveloads;
1723
1724 /* Build a key lookup mapping based on the available fields. */
1725 std::map<std::string, const SaveLoad *> key_lookup;
1726 for (auto &sld : slt) {
1727 if (!SlIsObjectValidInSavegame(sld)) continue;
1728
1729 /* Check that there is only one active SaveLoad for a given name. */
1730 assert(key_lookup.find(sld.name) == key_lookup.end());
1731 key_lookup[sld.name] = &sld;
1732 }
1733
1734 while (true) {
1735 uint8_t type = 0;
1736 SlSaveLoadConv(&type, SLE_UINT8);
1737 if (type == SLE_FILE_END) break;
1738
1739 std::string key;
1740 SlStdString(&key, SLE_STR);
1741
1742 auto sld_it = key_lookup.find(key);
1743 if (sld_it == key_lookup.end()) {
1744 /* SLA_LOADCHECK triggers this debug statement a lot and is perfectly normal. */
1745 Debug(sl, _sl.action == SLA_LOAD ? 2 : 6, "Field '{}' of type 0x{:02x} not found, skipping", key, type);
1746
1747 std::shared_ptr<SaveLoadHandler> handler = nullptr;
1748 SaveLoadType saveload_type;
1749 switch (type & SLE_FILE_TYPE_MASK) {
1750 case SLE_FILE_STRING:
1751 /* Strings are always marked with SLE_FILE_HAS_LENGTH_FIELD, as they are a list of chars. */
1752 saveload_type = SL_STDSTR;
1753 break;
1754
1755 case SLE_FILE_STRUCT:
1756 /* Structs are always marked with SLE_FILE_HAS_LENGTH_FIELD as SL_STRUCT is seen as a list of 0/1 in length. */
1757 saveload_type = SL_STRUCTLIST;
1758 handler = std::make_shared<SlSkipHandler>();
1759 break;
1760
1761 default:
1762 saveload_type = (type & SLE_FILE_HAS_LENGTH_FIELD) ? SL_ARR : SL_VAR;
1763 break;
1764 }
1765
1766 /* We don't know this field, so read to nothing. */
1767 saveloads.push_back({key, saveload_type, ((VarType)type & SLE_FILE_TYPE_MASK) | SLE_VAR_NULL, 1, SL_MIN_VERSION, SL_MAX_VERSION, 0, nullptr, 0, handler});
1768 continue;
1769 }
1770
1771 /* Validate the type of the field. If it is changed, the
1772 * savegame should have been bumped so we know how to do the
1773 * conversion. If this error triggers, that clearly didn't
1774 * happen and this is a friendly poke to the developer to bump
1775 * the savegame version and add conversion code. */
1776 uint8_t correct_type = GetSavegameFileType(*sld_it->second);
1777 if (correct_type != type) {
1778 Debug(sl, 1, "Field type for '{}' was expected to be 0x{:02x} but 0x{:02x} was found", key, correct_type, type);
1779 SlErrorCorrupt("Field type is different than expected");
1780 }
1781 saveloads.push_back(*sld_it->second);
1782 }
1783
1784 for (auto &sld : saveloads) {
1785 if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1786 sld.handler->load_description = SlTableHeader(sld.handler->GetDescription());
1787 }
1788 }
1789
1790 return saveloads;
1791 }
1792
1793 case SLA_SAVE: {
1794 /* Automatically calculate the length? */
1795 if (_sl.need_length != NL_NONE) {
1796 SlSetLength(SlCalcTableHeader(slt));
1797 if (_sl.need_length == NL_CALCLENGTH) break;
1798 }
1799
1800 for (auto &sld : slt) {
1801 if (!SlIsObjectValidInSavegame(sld)) continue;
1802 /* Make sure we are not storing empty keys. */
1803 assert(!sld.name.empty());
1804
1805 uint8_t type = GetSavegameFileType(sld);
1806 assert(type != SLE_FILE_END);
1807
1808 SlSaveLoadConv(&type, SLE_UINT8);
1809 SlStdString(const_cast<std::string *>(&sld.name), SLE_STR);
1810 }
1811
1812 /* Add an end-of-header marker. */
1813 uint8_t type = SLE_FILE_END;
1814 SlSaveLoadConv(&type, SLE_UINT8);
1815
1816 /* After the table, write down any sub-tables we might have. */
1817 for (auto &sld : slt) {
1818 if (!SlIsObjectValidInSavegame(sld)) continue;
1819 if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1820 /* SlCalcTableHeader already looks in sub-lists, so avoid the length being added twice. */
1821 NeedLength old_need_length = _sl.need_length;
1822 _sl.need_length = NL_NONE;
1823
1824 SlTableHeader(sld.handler->GetDescription());
1825
1826 _sl.need_length = old_need_length;
1827 }
1828 }
1829
1830 break;
1831 }
1832
1833 default: NOT_REACHED();
1834 }
1835
1836 return std::vector<SaveLoad>();
1837 }
1838
1852 std::vector<SaveLoad> SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
1853 {
1854 assert(_sl.action == SLA_LOAD || _sl.action == SLA_LOAD_CHECK);
1855 /* CH_TABLE / CH_SPARSE_TABLE always have a header. */
1856 if (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE) return SlTableHeader(slt);
1857
1858 std::vector<SaveLoad> saveloads;
1859
1860 /* Build a key lookup mapping based on the available fields. */
1861 std::map<std::string, std::vector<const SaveLoad *>> key_lookup;
1862 for (auto &sld : slt) {
1863 /* All entries should have a name; otherwise the entry should just be removed. */
1864 assert(!sld.name.empty());
1865
1866 key_lookup[sld.name].push_back(&sld);
1867 }
1868
1869 for (auto &slc : slct) {
1870 if (slc.name.empty()) {
1871 /* In old savegames there can be data we no longer care for. We
1872 * skip this by simply reading the amount of bytes indicated and
1873 * send those to /dev/null. */
1874 saveloads.push_back({"", SL_NULL, GetVarFileType(slc.null_type) | SLE_VAR_NULL, slc.null_length, slc.version_from, slc.version_to, 0, nullptr, 0, nullptr});
1875 } else {
1876 auto sld_it = key_lookup.find(slc.name);
1877 /* If this branch triggers, it means that an entry in the
1878 * SaveLoadCompat list is not mentioned in the SaveLoad list. Did
1879 * you rename a field in one and not in the other? */
1880 if (sld_it == key_lookup.end()) {
1881 /* This isn't an assert, as that leaves no information what
1882 * field was to blame. This way at least we have breadcrumbs. */
1883 Debug(sl, 0, "internal error: saveload compatibility field '{}' not found", slc.name);
1884 SlErrorCorrupt("Internal error with savegame compatibility");
1885 }
1886 for (auto &sld : sld_it->second) {
1887 saveloads.push_back(*sld);
1888 }
1889 }
1890 }
1891
1892 for (auto &sld : saveloads) {
1893 if (!SlIsObjectValidInSavegame(sld)) continue;
1894 if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1895 sld.handler->load_description = SlCompatTableHeader(sld.handler->GetDescription(), sld.handler->GetCompatDescription());
1896 }
1897 }
1898
1899 return saveloads;
1900 }
1901
1906 void SlGlobList(const SaveLoadTable &slt)
1907 {
1908 SlObject(nullptr, slt);
1909 }
1910
1916 void SlAutolength(AutolengthProc *proc, void *arg)
1917 {
1918 assert(_sl.action == SLA_SAVE);
1919
1920 /* Tell it to calculate the length */
1921 _sl.need_length = NL_CALCLENGTH;
1922 _sl.obj_len = 0;
1923 proc(arg);
1924
1925 /* Setup length */
1926 _sl.need_length = NL_WANTLENGTH;
1927 SlSetLength(_sl.obj_len);
1928
1929 size_t start_pos = _sl.dumper->GetSize();
1930 size_t expected_offs = start_pos + _sl.obj_len;
1931
1932 /* And write the stuff */
1933 proc(arg);
1934
1935 if (expected_offs != _sl.dumper->GetSize()) {
1936 SlErrorCorruptFmt("Invalid chunk size when writing autolength block, expected {}, got {}", _sl.obj_len, _sl.dumper->GetSize() - start_pos);
1937 }
1938 }
1939
1940 void ChunkHandler::LoadCheck(size_t len) const
1941 {
1942 switch (_sl.block_mode) {
1943 case CH_TABLE:
1944 case CH_SPARSE_TABLE:
1945 SlTableHeader({});
1946 [[fallthrough]];
1947 case CH_ARRAY:
1948 case CH_SPARSE_ARRAY:
1949 SlSkipArray();
1950 break;
1951 case CH_RIFF:
1952 SlSkipBytes(len);
1953 break;
1954 default:
1955 NOT_REACHED();
1956 }
1957 }
1958
1963 static void SlLoadChunk(const ChunkHandler &ch)
1964 {
1965 byte m = SlReadByte();
1966
1967 _sl.block_mode = m & CH_TYPE_MASK;
1968 _sl.obj_len = 0;
1969 _sl.expect_table_header = (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
1970
1971 /* The header should always be at the start. Read the length; the
1972 * Load() should as first action process the header. */
1973 if (_sl.expect_table_header) {
1974 SlIterateArray();
1975 }
1976
1977 switch (_sl.block_mode) {
1978 case CH_TABLE:
1979 case CH_ARRAY:
1980 _sl.array_index = 0;
1981 ch.Load();
1982 if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
1983 break;
1984 case CH_SPARSE_TABLE:
1985 case CH_SPARSE_ARRAY:
1986 ch.Load();
1987 if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
1988 break;
1989 case CH_RIFF: {
1990 /* Read length */
1991 size_t len = (SlReadByte() << 16) | ((m >> 4) << 24);
1992 len += SlReadUint16();
1993 _sl.obj_len = len;
1994 size_t start_pos = _sl.reader->GetSize();
1995 size_t endoffs = start_pos + len;
1996 ch.Load();
1997
1998 if (_sl.reader->GetSize() != endoffs) {
1999 SlErrorCorruptFmt("Invalid chunk size in RIFF in {} - expected {}, got {}", ch.GetName(), len, _sl.reader->GetSize() - start_pos);
2000 }
2001 break;
2002 }
2003 default:
2004 SlErrorCorrupt("Invalid chunk type");
2005 break;
2006 }
2007
2008 if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2009 }
2010
2016 static void SlLoadCheckChunk(const ChunkHandler &ch)
2017 {
2018 byte m = SlReadByte();
2019
2020 _sl.block_mode = m & CH_TYPE_MASK;
2021 _sl.obj_len = 0;
2022 _sl.expect_table_header = (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
2023
2024 /* The header should always be at the start. Read the length; the
2025 * LoadCheck() should as first action process the header. */
2026 if (_sl.expect_table_header) {
2027 SlIterateArray();
2028 }
2029
2030 switch (_sl.block_mode) {
2031 case CH_TABLE:
2032 case CH_ARRAY:
2033 _sl.array_index = 0;
2034 ch.LoadCheck();
2035 break;
2036 case CH_SPARSE_TABLE:
2037 case CH_SPARSE_ARRAY:
2038 ch.LoadCheck();
2039 break;
2040 case CH_RIFF: {
2041 /* Read length */
2042 size_t len = (SlReadByte() << 16) | ((m >> 4) << 24);
2043 len += SlReadUint16();
2044 _sl.obj_len = len;
2045 size_t start_pos = _sl.reader->GetSize();
2046 size_t endoffs = start_pos + len;
2047 ch.LoadCheck(len);
2048
2049 if (_sl.reader->GetSize() != endoffs) {
2050 SlErrorCorruptFmt("Invalid chunk size in RIFF in {} - expected {}, got {}", ch.GetName(), len, _sl.reader->GetSize() - start_pos);
2051 }
2052 break;
2053 }
2054 default:
2055 SlErrorCorrupt("Invalid chunk type");
2056 break;
2057 }
2058
2059 if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2060 }
2061
2067 static void SlSaveChunk(const ChunkHandler &ch)
2068 {
2069 if (ch.type == CH_READONLY) return;
2070
2071 SlWriteUint32(ch.id);
2072 Debug(sl, 2, "Saving chunk {}", ch.GetName());
2073
2074 _sl.block_mode = ch.type;
2075 _sl.expect_table_header = (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
2076
2077 _sl.need_length = (_sl.expect_table_header || _sl.block_mode == CH_RIFF) ? NL_WANTLENGTH : NL_NONE;
2078
2079 switch (_sl.block_mode) {
2080 case CH_RIFF:
2081 ch.Save();
2082 break;
2083 case CH_TABLE:
2084 case CH_ARRAY:
2085 _sl.last_array_index = 0;
2086 SlWriteByte(_sl.block_mode);
2087 ch.Save();
2088 SlWriteArrayLength(0); // Terminate arrays
2089 break;
2090 case CH_SPARSE_TABLE:
2091 case CH_SPARSE_ARRAY:
2092 SlWriteByte(_sl.block_mode);
2093 ch.Save();
2094 SlWriteArrayLength(0); // Terminate arrays
2095 break;
2096 default: NOT_REACHED();
2097 }
2098
2099 if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2100 }
2101
2103 static void SlSaveChunks()
2104 {
2105 for (auto &ch : ChunkHandlers()) {
2106 SlSaveChunk(ch);
2107 }
2108
2109 /* Terminator */
2110 SlWriteUint32(0);
2111 }
2112
2119 static const ChunkHandler *SlFindChunkHandler(uint32_t id)
2120 {
2121 for (const ChunkHandler &ch : ChunkHandlers()) if (ch.id == id) return &ch;
2122 return nullptr;
2123 }
2124
2126 static void SlLoadChunks()
2127 {
2128 uint32_t id;
2129 const ChunkHandler *ch;
2130
2131 for (id = SlReadUint32(); id != 0; id = SlReadUint32()) {
2132 Debug(sl, 2, "Loading chunk {:c}{:c}{:c}{:c}", id >> 24, id >> 16, id >> 8, id);
2133
2134 ch = SlFindChunkHandler(id);
2135 if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2136 SlLoadChunk(*ch);
2137 }
2138 }
2139
2141 static void SlLoadCheckChunks()
2142 {
2143 uint32_t id;
2144 const ChunkHandler *ch;
2145
2146 for (id = SlReadUint32(); id != 0; id = SlReadUint32()) {
2147 Debug(sl, 2, "Loading chunk {:c}{:c}{:c}{:c}", id >> 24, id >> 16, id >> 8, id);
2148
2149 ch = SlFindChunkHandler(id);
2150 if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2151 SlLoadCheckChunk(*ch);
2152 }
2153 }
2154
2156 static void SlFixPointers()
2157 {
2158 _sl.action = SLA_PTRS;
2159
2160 for (const ChunkHandler &ch : ChunkHandlers()) {
2161 Debug(sl, 3, "Fixing pointers for {}", ch.GetName());
2162 ch.FixPointers();
2163 }
2164
2165 assert(_sl.action == SLA_PTRS);
2166 }
2167
2168
2170 struct FileReader : LoadFilter {
2171 FILE *file;
2172 long begin;
2173
2178 FileReader(FILE *file) : LoadFilter(nullptr), file(file), begin(ftell(file))
2179 {
2180 }
2181
2183 ~FileReader()
2184 {
2185 if (this->file != nullptr) {
2186 _game_session_stats.savegame_size = ftell(this->file) - this->begin;
2187 fclose(this->file);
2188 }
2189 this->file = nullptr;
2190 }
2191
2192 size_t Read(byte *buf, size_t size) override
2193 {
2194 /* We're in the process of shutting down, i.e. in "failure" mode. */
2195 if (this->file == nullptr) return 0;
2196
2197 return fread(buf, 1, size, this->file);
2198 }
2199
2200 void Reset() override
2201 {
2202 clearerr(this->file);
2203 if (fseek(this->file, this->begin, SEEK_SET)) {
2204 Debug(sl, 1, "Could not reset the file reading");
2205 }
2206 }
2207 };
2208
2210 struct FileWriter : SaveFilter {
2211 FILE *file;
2212
2217 FileWriter(FILE *file) : SaveFilter(nullptr), file(file)
2218 {
2219 }
2220
2222 ~FileWriter()
2223 {
2224 this->Finish();
2225 }
2226
2227 void Write(byte *buf, size_t size) override
2228 {
2229 /* We're in the process of shutting down, i.e. in "failure" mode. */
2230 if (this->file == nullptr) return;
2231
2232 if (fwrite(buf, 1, size, this->file) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
2233 }
2234
2235 void Finish() override
2236 {
2237 if (this->file != nullptr) {
2238 _game_session_stats.savegame_size = ftell(this->file);
2239 fclose(this->file);
2240 }
2241 this->file = nullptr;
2242 }
2243 };
2244
2245 /*******************************************
2246 ********** START OF LZO CODE **************
2247 *******************************************/
2248
2249 #ifdef WITH_LZO
2250 #include <lzo/lzo1x.h>
2251
2253 static const uint LZO_BUFFER_SIZE = 8192;
2254
2256 struct LZOLoadFilter : LoadFilter {
2261 LZOLoadFilter(std::shared_ptr<LoadFilter> chain) : LoadFilter(chain)
2262 {
2263 if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2264 }
2265
2266 size_t Read(byte *buf, size_t ssize) override
2267 {
2268 assert(ssize >= LZO_BUFFER_SIZE);
2269
2270 /* Buffer size is from the LZO docs plus the chunk header size. */
2271 byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32_t) * 2];
2272 uint32_t tmp[2];
2273 uint32_t size;
2274 lzo_uint len = ssize;
2275
2276 /* Read header*/
2277 if (this->chain->Read((byte*)tmp, sizeof(tmp)) != sizeof(tmp)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE, "File read failed");
2278
2279 /* Check if size is bad */
2280 ((uint32_t*)out)[0] = size = tmp[1];
2281
2282 if (_sl_version != SL_MIN_VERSION) {
2283 tmp[0] = TO_BE32(tmp[0]);
2284 size = TO_BE32(size);
2285 }
2286
2287 if (size >= sizeof(out)) SlErrorCorrupt("Inconsistent size");
2288
2289 /* Read block */
2290 if (this->chain->Read(out + sizeof(uint32_t), size) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2291
2292 /* Verify checksum */
2293 if (tmp[0] != lzo_adler32(0, out, size + sizeof(uint32_t))) SlErrorCorrupt("Bad checksum");
2294
2295 /* Decompress */
2296 int ret = lzo1x_decompress_safe(out + sizeof(uint32_t) * 1, size, buf, &len, nullptr);
2297 if (ret != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2298 return len;
2299 }
2300 };
2301
2303 struct LZOSaveFilter : SaveFilter {
2308 LZOSaveFilter(std::shared_ptr<SaveFilter> chain, byte) : SaveFilter(chain)
2309 {
2310 if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2311 }
2312
2313 void Write(byte *buf, size_t size) override
2314 {
2315 const lzo_bytep in = buf;
2316 /* Buffer size is from the LZO docs plus the chunk header size. */
2317 byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32_t) * 2];
2318 byte wrkmem[LZO1X_1_MEM_COMPRESS];
2319 lzo_uint outlen;
2320
2321 do {
2322 /* Compress up to LZO_BUFFER_SIZE bytes at once. */
2323 lzo_uint len = size > LZO_BUFFER_SIZE ? LZO_BUFFER_SIZE : (lzo_uint)size;
2324 lzo1x_1_compress(in, len, out + sizeof(uint32_t) * 2, &outlen, wrkmem);
2325 ((uint32_t*)out)[1] = TO_BE32((uint32_t)outlen);
2326 ((uint32_t*)out)[0] = TO_BE32(lzo_adler32(0, out + sizeof(uint32_t), outlen + sizeof(uint32_t)));
2327 this->chain->Write(out, outlen + sizeof(uint32_t) * 2);
2328
2329 /* Move to next data chunk. */
2330 size -= len;
2331 in += len;
2332 } while (size > 0);
2333 }
2334 };
2335
2336 #endif /* WITH_LZO */
2337
2338 /*********************************************
2339 ******** START OF NOCOMP CODE (uncompressed)*
2340 *********************************************/
2341
2343 struct NoCompLoadFilter : LoadFilter {
2348 NoCompLoadFilter(std::shared_ptr<LoadFilter> chain) : LoadFilter(chain)
2349 {
2350 }
2351
2352 size_t Read(byte *buf, size_t size) override
2353 {
2354 return this->chain->Read(buf, size);
2355 }
2356 };
2357
2359 struct NoCompSaveFilter : SaveFilter {
2364 NoCompSaveFilter(std::shared_ptr<SaveFilter> chain, byte) : SaveFilter(chain)
2365 {
2366 }
2367
2368 void Write(byte *buf, size_t size) override
2369 {
2370 this->chain->Write(buf, size);
2371 }
2372 };
2373
2374 /********************************************
2375 ********** START OF ZLIB CODE **************
2376 ********************************************/
2377
2378 #if defined(WITH_ZLIB)
2379 #include <zlib.h>
2380
2382 struct ZlibLoadFilter : LoadFilter {
2383 z_stream z;
2384 byte fread_buf[MEMORY_CHUNK_SIZE];
2385
2390 ZlibLoadFilter(std::shared_ptr<LoadFilter> chain) : LoadFilter(chain)
2391 {
2392 memset(&this->z, 0, sizeof(this->z));
2393 if (inflateInit(&this->z) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2394 }
2395
2397 ~ZlibLoadFilter()
2398 {
2399 inflateEnd(&this->z);
2400 }
2401
2402 size_t Read(byte *buf, size_t size) override
2403 {
2404 this->z.next_out = buf;
2405 this->z.avail_out = (uint)size;
2406
2407 do {
2408 /* read more bytes from the file? */
2409 if (this->z.avail_in == 0) {
2410 this->z.next_in = this->fread_buf;
2411 this->z.avail_in = (uint)this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2412 }
2413
2414 /* inflate the data */
2415 int r = inflate(&this->z, 0);
2416 if (r == Z_STREAM_END) break;
2417
2418 if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "inflate() failed");
2419 } while (this->z.avail_out != 0);
2420
2421 return size - this->z.avail_out;
2422 }
2423 };
2424
2426 struct ZlibSaveFilter : SaveFilter {
2427 z_stream z;
2428 byte fwrite_buf[MEMORY_CHUNK_SIZE];
2429
2435 ZlibSaveFilter(std::shared_ptr<SaveFilter> chain, byte compression_level) : SaveFilter(chain)
2436 {
2437 memset(&this->z, 0, sizeof(this->z));
2438 if (deflateInit(&this->z, compression_level) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2439 }
2440
2442 ~ZlibSaveFilter()
2443 {
2444 deflateEnd(&this->z);
2445 }
2446
2453 void WriteLoop(byte *p, size_t len, int mode)
2454 {
2455 uint n;
2456 this->z.next_in = p;
2457 this->z.avail_in = (uInt)len;
2458 do {
2459 this->z.next_out = this->fwrite_buf;
2460 this->z.avail_out = sizeof(this->fwrite_buf);
2461
2469 int r = deflate(&this->z, mode);
2470
2471 /* bytes were emitted? */
2472 if ((n = sizeof(this->fwrite_buf) - this->z.avail_out) != 0) {
2473 this->chain->Write(this->fwrite_buf, n);
2474 }
2475 if (r == Z_STREAM_END) break;
2476
2477 if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "zlib returned error code");
2478 } while (this->z.avail_in || !this->z.avail_out);
2479 }
2480
2481 void Write(byte *buf, size_t size) override
2482 {
2483 this->WriteLoop(buf, size, 0);
2484 }
2485
2486 void Finish() override
2487 {
2488 this->WriteLoop(nullptr, 0, Z_FINISH);
2489 this->chain->Finish();
2490 }
2491 };
2492
2493 #endif /* WITH_ZLIB */
2494
2495 /********************************************
2496 ********** START OF LZMA CODE **************
2497 ********************************************/
2498
2499 #if defined(WITH_LIBLZMA)
2500 #include <lzma.h>
2501
2508 static const lzma_stream _lzma_init = LZMA_STREAM_INIT;
2509
2511 struct LZMALoadFilter : LoadFilter {
2512 lzma_stream lzma;
2513 byte fread_buf[MEMORY_CHUNK_SIZE];
2514
2519 LZMALoadFilter(std::shared_ptr<LoadFilter> chain) : LoadFilter(chain), lzma(_lzma_init)
2520 {
2521 /* Allow saves up to 256 MB uncompressed */
2522 if (lzma_auto_decoder(&this->lzma, 1 << 28, 0) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2523 }
2524
2526 ~LZMALoadFilter()
2527 {
2528 lzma_end(&this->lzma);
2529 }
2530
2531 size_t Read(byte *buf, size_t size) override
2532 {
2533 this->lzma.next_out = buf;
2534 this->lzma.avail_out = size;
2535
2536 do {
2537 /* read more bytes from the file? */
2538 if (this->lzma.avail_in == 0) {
2539 this->lzma.next_in = this->fread_buf;
2540 this->lzma.avail_in = this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2541 }
2542
2543 /* inflate the data */
2544 lzma_ret r = lzma_code(&this->lzma, LZMA_RUN);
2545 if (r == LZMA_STREAM_END) break;
2546 if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2547 } while (this->lzma.avail_out != 0);
2548
2549 return size - this->lzma.avail_out;
2550 }
2551 };
2552
2554 struct LZMASaveFilter : SaveFilter {
2555 lzma_stream lzma;
2556 byte fwrite_buf[MEMORY_CHUNK_SIZE];
2557
2563 LZMASaveFilter(std::shared_ptr<SaveFilter> chain, byte compression_level) : SaveFilter(chain), lzma(_lzma_init)
2564 {
2565 if (lzma_easy_encoder(&this->lzma, compression_level, LZMA_CHECK_CRC32) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2566 }
2567
2569 ~LZMASaveFilter()
2570 {
2571 lzma_end(&this->lzma);
2572 }
2573
2580 void WriteLoop(byte *p, size_t len, lzma_action action)
2581 {
2582 size_t n;
2583 this->lzma.next_in = p;
2584 this->lzma.avail_in = len;
2585 do {
2586 this->lzma.next_out = this->fwrite_buf;
2587 this->lzma.avail_out = sizeof(this->fwrite_buf);
2588
2589 lzma_ret r = lzma_code(&this->lzma, action);
2590
2591 /* bytes were emitted? */
2592 if ((n = sizeof(this->fwrite_buf) - this->lzma.avail_out) != 0) {
2593 this->chain->Write(this->fwrite_buf, n);
2594 }
2595 if (r == LZMA_STREAM_END) break;
2596 if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2597 } while (this->lzma.avail_in || !this->lzma.avail_out);
2598 }
2599
2600 void Write(byte *buf, size_t size) override
2601 {
2602 this->WriteLoop(buf, size, LZMA_RUN);
2603 }
2604
2605 void Finish() override
2606 {
2607 this->WriteLoop(nullptr, 0, LZMA_FINISH);
2608 this->chain->Finish();
2609 }
2610 };
2611
2612 #endif /* WITH_LIBLZMA */
2613
2614 /*******************************************
2615 ************* END OF CODE *****************
2616 *******************************************/
2617
2619 struct SaveLoadFormat {
2620 const char *name;
2621 uint32_t tag;
2622
2623 std::shared_ptr<LoadFilter> (*init_load)(std::shared_ptr<LoadFilter> chain);
2624 std::shared_ptr<SaveFilter> (*init_write)(std::shared_ptr<SaveFilter> chain, byte compression);
2625
2626 byte min_compression;
2627 byte default_compression;
2628 byte max_compression;
2629 };
2630
2632 static const SaveLoadFormat _saveload_formats[] = {
2633 #if defined(WITH_LZO)
2634 /* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
2635 {"lzo", TO_BE32X('OTTD'), CreateLoadFilter<LZOLoadFilter>, CreateSaveFilter<LZOSaveFilter>, 0, 0, 0},
2636 #else
2637 {"lzo", TO_BE32X('OTTD'), nullptr, nullptr, 0, 0, 0},
2638 #endif
2639 /* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
2640 {"none", TO_BE32X('OTTN'), CreateLoadFilter<NoCompLoadFilter>, CreateSaveFilter<NoCompSaveFilter>, 0, 0, 0},
2641 #if defined(WITH_ZLIB)
2642 /* After level 6 the speed reduction is significant (1.5x to 2.5x slower per level), but the reduction in filesize is
2643 * fairly insignificant (~1% for each step). Lower levels become ~5-10% bigger by each level than level 6 while level
2644 * 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
2645 {"zlib", TO_BE32X('OTTZ'), CreateLoadFilter<ZlibLoadFilter>, CreateSaveFilter<ZlibSaveFilter>, 0, 6, 9},
2646 #else
2647 {"zlib", TO_BE32X('OTTZ'), nullptr, nullptr, 0, 0, 0},
2648 #endif
2649 #if defined(WITH_LIBLZMA)
2650 /* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
2651 * Higher compression levels are possible, and might improve savegame size by up to 25%, but are also up to 10 times slower.
2652 * The next significant reduction in file size is at level 4, but that is already 4 times slower. Level 3 is primarily 50%
2653 * slower while not improving the filesize, while level 0 and 1 are faster, but don't reduce savegame size much.
2654 * It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
2655 {"lzma", TO_BE32X('OTTX'), CreateLoadFilter<LZMALoadFilter>, CreateSaveFilter<LZMASaveFilter>, 0, 2, 9},
2656 #else
2657 {"lzma", TO_BE32X('OTTX'), nullptr, nullptr, 0, 0, 0},
2658 #endif
2659 };
2660
2668 static const SaveLoadFormat *GetSavegameFormat(const std::string &full_name, byte *compression_level)
2669 {
2670 const SaveLoadFormat *def = lastof(_saveload_formats);
2671
2672 /* find default savegame format, the highest one with which files can be written */
2673 while (!def->init_write) def--;
2674
2675 if (!full_name.empty()) {
2676 /* Get the ":..." of the compression level out of the way */
2677 size_t separator = full_name.find(':');
2678 bool has_comp_level = separator != std::string::npos;
2679 const std::string name(full_name, 0, has_comp_level ? separator : full_name.size());
2680
2681 for (const SaveLoadFormat *slf = &_saveload_formats[0]; slf != endof(_saveload_formats); slf++) {
2682 if (slf->init_write != nullptr && name.compare(slf->name) == 0) {
2683 *compression_level = slf->default_compression;
2684 if (has_comp_level) {
2685 const std::string complevel(full_name, separator + 1);
2686
2687 /* Get the level and determine whether all went fine. */
2688 size_t processed;
2689 long level = std::stol(complevel, &processed, 10);
2690 if (processed == 0 || level != Clamp(level, slf->min_compression, slf->max_compression)) {
2691 SetDParamStr(0, complevel);
2692 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_LEVEL, WL_CRITICAL);
2693 } else {
2694 *compression_level = level;
2695 }
2696 }
2697 return slf;
2698 }
2699 }
2700
2701 SetDParamStr(0, name);
2702 SetDParamStr(1, def->name);
2703 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM, WL_CRITICAL);
2704 }
2705 *compression_level = def->default_compression;
2706 return def;
2707 }
2708
2709 /* actual loader/saver function */
2710 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
2711 extern bool AfterLoadGame();
2712 extern bool LoadOldSaveGame(const std::string &file);
2713
2717 static void ResetSaveloadData()
2718 {
2719 ResetTempEngineData();
2720 ResetLabelMaps();
2721 ResetOldWaypoints();
2722 }
2723
2727 static inline void ClearSaveLoadState()
2728 {
2729 _sl.dumper = nullptr;
2730 _sl.sf = nullptr;
2731 _sl.reader = nullptr;
2732 _sl.lf = nullptr;
2733 }
2734
2736 static void SaveFileStart()
2737 {
2738 SetMouseCursorBusy(true);
2739
2740 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SAVELOAD_START);
2741 _sl.saveinprogress = true;
2742 }
2743
2745 static void SaveFileDone()
2746 {
2747 SetMouseCursorBusy(false);
2748
2749 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SAVELOAD_FINISH);
2750 _sl.saveinprogress = false;
2751
2752 #ifdef __EMSCRIPTEN__
2753 EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
2754 #endif
2755 }
2756
2758 void SetSaveLoadError(StringID str)
2759 {
2760 _sl.error_str = str;
2761 }
2762
2764 const char *GetSaveLoadErrorString()
2765 {
2766 SetDParam(0, _sl.error_str);
2767 SetDParamStr(1, _sl.extra_msg);
2768
2769 static std::string err_str;
2770 err_str = GetString(_sl.action == SLA_SAVE ? STR_ERROR_GAME_SAVE_FAILED : STR_ERROR_GAME_LOAD_FAILED);
2771 return err_str.c_str();
2772 }
2773
2775 static void SaveFileError()
2776 {
2777 SetDParamStr(0, GetSaveLoadErrorString());
2778 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
2779 SaveFileDone();
2780 }
2781
2786 static SaveOrLoadResult SaveFileToDisk(bool threaded)
2787 {
2788 try {
2789 byte compression;
2790 const SaveLoadFormat *fmt = GetSavegameFormat(_savegame_format, &compression);
2791
2792 /* We have written our stuff to memory, now write it to file! */
2793 uint32_t hdr[2] = { fmt->tag, TO_BE32(SAVEGAME_VERSION << 16) };
2794 _sl.sf->Write((byte*)hdr, sizeof(hdr));
2795
2796 _sl.sf = fmt->init_write(_sl.sf, compression);
2797 _sl.dumper->Flush(_sl.sf);
2798
2799 ClearSaveLoadState();
2800
2801 if (threaded) SetAsyncSaveFinish(SaveFileDone);
2802
2803 return SL_OK;
2804 } catch (...) {
2805 ClearSaveLoadState();
2806
2807 AsyncSaveFinishProc asfp = SaveFileDone;
2808
2809 /* We don't want to shout when saving is just
2810 * cancelled due to a client disconnecting. */
2811 if (_sl.error_str != STR_NETWORK_ERROR_LOSTCONNECTION) {
2812 /* Skip the "colour" character */
2813 Debug(sl, 0, "{}", GetSaveLoadErrorString() + 3);
2814 asfp = SaveFileError;
2815 }
2816
2817 if (threaded) {
2818 SetAsyncSaveFinish(asfp);
2819 } else {
2820 asfp();
2821 }
2822 return SL_ERROR;
2823 }
2824 }
2825
2826 void WaitTillSaved()
2827 {
2828 if (!_save_thread.joinable()) return;
2829
2830 _save_thread.join();
2831
2832 /* Make sure every other state is handled properly as well. */
2833 ProcessAsyncSaveFinish();
2834 }
2835
2844 static SaveOrLoadResult DoSave(std::shared_ptr<SaveFilter> writer, bool threaded)
2845 {
2846 assert(!_sl.saveinprogress);
2847
2848 _sl.dumper = std::make_unique<MemoryDumper>();
2849 _sl.sf = writer;
2850
2851 _sl_version = SAVEGAME_VERSION;
2852
2853 SaveViewportBeforeSaveGame();
2854 SlSaveChunks();
2855
2856 SaveFileStart();
2857
2858 if (!threaded || !StartNewThread(&_save_thread, "ottd:savegame", &SaveFileToDisk, true)) {
2859 if (threaded) Debug(sl, 1, "Cannot create savegame thread, reverting to single-threaded mode...");
2860
2861 SaveOrLoadResult result = SaveFileToDisk(false);
2862 SaveFileDone();
2863
2864 return result;
2865 }
2866
2867 return SL_OK;
2868 }
2869
2876 SaveOrLoadResult SaveWithFilter(std::shared_ptr<SaveFilter> writer, bool threaded)
2877 {
2878 try {
2879 _sl.action = SLA_SAVE;
2880 return DoSave(writer, threaded);
2881 } catch (...) {
2882 ClearSaveLoadState();
2883 return SL_ERROR;
2884 }
2885 }
2886
2893 static SaveOrLoadResult DoLoad(std::shared_ptr<LoadFilter> reader, bool load_check)
2894 {
2895 _sl.lf = reader;
2896
2897 if (load_check) {
2898 /* Clear previous check data */
2899 _load_check_data.Clear();
2900 /* Mark SL_LOAD_CHECK as supported for this savegame. */
2901 _load_check_data.checkable = true;
2902 }
2903
2904 uint32_t hdr[2];
2905 if (_sl.lf->Read((byte*)hdr, sizeof(hdr)) != sizeof(hdr)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2906
2907 /* see if we have any loader for this type. */
2908 const SaveLoadFormat *fmt = _saveload_formats;
2909 for (;;) {
2910 /* No loader found, treat as version 0 and use LZO format */
2911 if (fmt == endof(_saveload_formats)) {
2912 Debug(sl, 0, "Unknown savegame type, trying to load it as the buggy format");
2913 _sl.lf->Reset();
2914 _sl_version = SL_MIN_VERSION;
2915 _sl_minor_version = 0;
2916
2917 /* Try to find the LZO savegame format; it uses 'OTTD' as tag. */
2918 fmt = _saveload_formats;
2919 for (;;) {
2920 if (fmt == endof(_saveload_formats)) {
2921 /* Who removed LZO support? */
2922 NOT_REACHED();
2923 }
2924 if (fmt->tag == TO_BE32X('OTTD')) break;
2925 fmt++;
2926 }
2927 break;
2928 }
2929
2930 if (fmt->tag == hdr[0]) {
2931 /* check version number */
2932 _sl_version = (SaveLoadVersion)(TO_BE32(hdr[1]) >> 16);
2933 /* Minor is not used anymore from version 18.0, but it is still needed
2934 * in versions before that (4 cases) which can't be removed easy.
2935 * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */
2936 _sl_minor_version = (TO_BE32(hdr[1]) >> 8) & 0xFF;
2937
2938 Debug(sl, 1, "Loading savegame version {}", _sl_version);
2939
2940 /* Is the version higher than the current? */
2941 if (_sl_version > SAVEGAME_VERSION) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME);
2942 if (_sl_version >= SLV_START_PATCHPACKS && _sl_version <= SLV_END_PATCHPACKS) SlError(STR_GAME_SAVELOAD_ERROR_PATCHPACK);
2943 break;
2944 }
2945
2946 fmt++;
2947 }
2948
2949 /* loader for this savegame type is not implemented? */
2950 if (fmt->init_load == nullptr) {
2951 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, fmt::format("Loader for '{}' is not available.", fmt->name));
2952 }
2953
2954 _sl.lf = fmt->init_load(_sl.lf);
2955 _sl.reader = std::make_unique<ReadBuffer>(_sl.lf);
2956 _next_offs = 0;
2957
2958 if (!load_check) {
2959 ResetSaveloadData();
2960
2961 /* Old maps were hardcoded to 256x256 and thus did not contain
2962 * any mapsize information. Pre-initialize to 256x256 to not to
2963 * confuse old games */
2964 InitializeGame(256, 256, true, true);
2965
2966 _gamelog.Reset();
2967
2968 if (IsSavegameVersionBefore(SLV_4)) {
2969 /*
2970 * NewGRFs were introduced between 0.3,4 and 0.3.5, which both
2971 * shared savegame version 4. Anything before that 'obviously'
2972 * does not have any NewGRFs. Between the introduction and
2973 * savegame version 41 (just before 0.5) the NewGRF settings
2974 * were not stored in the savegame and they were loaded by
2975 * using the settings from the main menu.
2976 * So, to recap:
2977 * - savegame version < 4: do not load any NewGRFs.
2978 * - savegame version >= 41: load NewGRFs from savegame, which is
2979 * already done at this stage by
2980 * overwriting the main menu settings.
2981 * - other savegame versions: use main menu settings.
2982 *
2983 * This means that users *can* crash savegame version 4..40
2984 * savegames if they set incompatible NewGRFs in the main menu,
2985 * but can't crash anymore for savegame version < 4 savegames.
2986 *
2987 * Note: this is done here because AfterLoadGame is also called
2988 * for TTO/TTD/TTDP savegames which have their own NewGRF logic.
2989 */
2990 ClearGRFConfigList(&_grfconfig);
2991 }
2992 }
2993
2994 if (load_check) {
2995 /* Load chunks into _load_check_data.
2996 * No pools are loaded. References are not possible, and thus do not need resolving. */
2997 SlLoadCheckChunks();
2998 } else {
2999 /* Load chunks and resolve references */
3000 SlLoadChunks();
3001 SlFixPointers();
3002 }
3003
3004 ClearSaveLoadState();
3005
3006 _savegame_type = SGT_OTTD;
3007
3008 if (load_check) {
3009 /* The only part from AfterLoadGame() we need */
3010 _load_check_data.grf_compatibility = IsGoodGRFConfigList(_load_check_data.grfconfig);
3011 } else {
3012 _gamelog.StartAction(GLAT_LOAD);
3013
3014 /* After loading fix up savegame for any internal changes that
3015 * might have occurred since then. If it fails, load back the old game. */
3016 if (!AfterLoadGame()) {
3017 _gamelog.StopAction();
3018 return SL_REINIT;
3019 }
3020
3021 _gamelog.StopAction();
3022 }
3023
3024 return SL_OK;
3025 }
3026
3032 SaveOrLoadResult LoadWithFilter(std::shared_ptr<LoadFilter> reader)
3033 {
3034 try {
3035 _sl.action = SLA_LOAD;
3036 return DoLoad(reader, false);
3037 } catch (...) {
3038 ClearSaveLoadState();
3039 return SL_REINIT;
3040 }
3041 }
3042
3052 SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
3053 {
3054 /* An instance of saving is already active, so don't go saving again */
3055 if (_sl.saveinprogress && fop == SLO_SAVE && dft == DFT_GAME_FILE && threaded) {
3056 /* if not an autosave, but a user action, show error message */
3057 if (!_do_autosave) ShowErrorMessage(STR_ERROR_SAVE_STILL_IN_PROGRESS, INVALID_STRING_ID, WL_ERROR);
3058 return SL_OK;
3059 }
3060 WaitTillSaved();
3061
3062 try {
3063 /* Load a TTDLX or TTDPatch game */
3064 if (fop == SLO_LOAD && dft == DFT_OLD_GAME_FILE) {
3065 ResetSaveloadData();
3066
3067 InitializeGame(256, 256, true, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
3068
3069 /* TTD/TTO savegames have no NewGRFs, TTDP savegame have them
3070 * and if so a new NewGRF list will be made in LoadOldSaveGame.
3071 * Note: this is done here because AfterLoadGame is also called
3072 * for OTTD savegames which have their own NewGRF logic. */
3073 ClearGRFConfigList(&_grfconfig);
3074 _gamelog.Reset();
3075 if (!LoadOldSaveGame(filename)) return SL_REINIT;
3076 _sl_version = SL_MIN_VERSION;
3077 _sl_minor_version = 0;
3078 _gamelog.StartAction(GLAT_LOAD);
3079 if (!AfterLoadGame()) {
3080 _gamelog.StopAction();
3081 return SL_REINIT;
3082 }
3083 _gamelog.StopAction();
3084 return SL_OK;
3085 }
3086
3087 assert(dft == DFT_GAME_FILE);
3088 switch (fop) {
3089 case SLO_CHECK:
3090 _sl.action = SLA_LOAD_CHECK;
3091 break;
3092
3093 case SLO_LOAD:
3094 _sl.action = SLA_LOAD;
3095 break;
3096
3097 case SLO_SAVE:
3098 _sl.action = SLA_SAVE;
3099 break;
3100
3101 default: NOT_REACHED();
3102 }
3103
3104 FILE *fh = (fop == SLO_SAVE) ? FioFOpenFile(filename, "wb", sb) : FioFOpenFile(filename, "rb", sb);
3105
3106 /* Make it a little easier to load savegames from the console */
3107 if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SAVE_DIR);
3108 if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", BASE_DIR);
3109 if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SCENARIO_DIR);
3110
3111 if (fh == nullptr) {
3112 SlError(fop == SLO_SAVE ? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE : STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3113 }
3114
3115 if (fop == SLO_SAVE) { // SAVE game
3116 Debug(desync, 1, "save: {:08x}; {:02x}; {}", TimerGameEconomy::date, TimerGameEconomy::date_fract, filename);
3117 if (!_settings_client.gui.threaded_saves) threaded = false;
3118
3119 return DoSave(std::make_shared<FileWriter>(fh), threaded);
3120 }
3121
3122 /* LOAD game */
3123 assert(fop == SLO_LOAD || fop == SLO_CHECK);
3124 Debug(desync, 1, "load: {}", filename);
3125 return DoLoad(std::make_shared<FileReader>(fh), fop == SLO_CHECK);
3126 } catch (...) {
3127 /* This code may be executed both for old and new save games. */
3128 ClearSaveLoadState();
3129
3130 /* Skip the "colour" character */
3131 if (fop != SLO_CHECK) Debug(sl, 0, "{}", GetSaveLoadErrorString() + 3);
3132
3133 /* A saver/loader exception!! reinitialize all variables to prevent crash! */
3134 return (fop == SLO_LOAD) ? SL_REINIT : SL_ERROR;
3135 }
3136 }
3137
3143 void DoAutoOrNetsave(FiosNumberedSaveName &counter)
3144 {
3145 std::string filename;
3146
3147 if (_settings_client.gui.keep_all_autosave) {
3148 filename = GenerateDefaultSaveName() + counter.Extension();
3149 } else {
3150 filename = counter.Filename();
3151 }
3152
3153 Debug(sl, 2, "Autosaving to '{}'", filename);
3154 if (SaveOrLoad(filename, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR) != SL_OK) {
3155 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
3156 }
3157 }
3158
3159
3161 void DoExitSave()
3162 {
3163 SaveOrLoad("exit.sav", SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR);
3164 }
3165
3169 std::string GenerateDefaultSaveName()
3170 {
3171 /* Check if we have a name for this map, which is the name of the first
3172 * available company. When there's no company available we'll use
3173 * 'Spectator' as "company" name. */
3174 CompanyID cid = _local_company;
3175 if (!Company::IsValidID(cid)) {
3176 for (const Company *c : Company::Iterate()) {
3177 cid = c->index;
3178 break;
3179 }
3180 }
3181
3182 SetDParam(0, cid);
3183
3184 /* We show the current game time differently depending on the timekeeping units used by this game. */
3185 if (TimerGameEconomy::UsingWallclockUnits()) {
3186 /* Insert time played. */
3187 const auto play_time = TimerGameTick::counter / Ticks::TICKS_PER_SECOND;
3188 SetDParam(1, STR_SAVEGAME_DURATION_REALTIME);
3189 SetDParam(2, play_time / 60 / 60);
3190 SetDParam(3, (play_time / 60) % 60);
3191 } else {
3192 /* Insert current date */
3193 switch (_settings_client.gui.date_format_in_default_names) {
3194 case 0: SetDParam(1, STR_JUST_DATE_LONG); break;
3195 case 1: SetDParam(1, STR_JUST_DATE_TINY); break;
3196 case 2: SetDParam(1, STR_JUST_DATE_ISO); break;
3197 default: NOT_REACHED();
3198 }
3199 SetDParam(2, TimerGameEconomy::date);
3200 }
3201
3202 /* Get the correct string (special string for when there's not company) */
3203 std::string filename = GetString(!Company::IsValidID(cid) ? STR_SAVEGAME_NAME_SPECTATOR : STR_SAVEGAME_NAME_DEFAULT);
3204 SanitizeFilename(filename);
3205 return filename;
3206 }
3207
3212 void FileToSaveLoad::SetMode(FiosType ft)
3213 {
3214 this->SetMode(SLO_LOAD, GetAbstractFileType(ft), GetDetailedFileType(ft));
3215 }
3216
3223 void FileToSaveLoad::SetMode(SaveLoadOperation fop, AbstractFileType aft, DetailedFileType dft)
3224 {
3225 if (aft == FT_INVALID || aft == FT_NONE) {
3226 this->file_op = SLO_INVALID;
3227 this->detail_ftype = DFT_INVALID;
3228 this->abstract_ftype = FT_INVALID;
3229 return;
3230 }
3231
3232 this->file_op = fop;
3233 this->detail_ftype = dft;
3234 this->abstract_ftype = aft;
3235 }
3236
3241 void FileToSaveLoad::Set(const FiosItem &item)
3242 {
3243 this->SetMode(item.type);
3244 this->name = item.name;
3245 this->title = item.title;
3246 }
3247
3248 SaveLoadTable SaveLoadHandler::GetLoadDescription() const
3249 {
3250 assert(this->load_description.has_value());
3251 return *this->load_description;
3252 }
SL_NULL
@ SL_NULL
Save null-bytes and load to nowhere.
Definition: saveload.h:691
ZlibLoadFilter::fread_buf
byte fread_buf[MEMORY_CHUNK_SIZE]
Buffer for reading from the file.
Definition: saveload.cpp:2386
SlLoadChunks
static void SlLoadChunks()
Load all chunks.
Definition: saveload.cpp:2126
SlCalcTableHeader
static size_t SlCalcTableHeader(const SaveLoadTable &slt)
Calculate the size of the table header.
Definition: saveload.cpp:1441
ResetSaveloadData
static void ResetSaveloadData()
Clear temporary data that is passed between various saveload phases.
Definition: saveload.cpp:2717
SlStorageHelper::SlSaveLoad
static void SlSaveLoad(void *storage, VarType conv, SaveLoadType cmd=SL_VAR)
Internal templated helper to save/load a list-like type.
Definition: saveload.cpp:1272
SaveLoadVersion
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
Definition: saveload.h:30
SetMouseCursorBusy
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
Definition: gfx.cpp:1689
SaveLoad::version_to
SaveLoadVersion version_to
Save/load the variable before this savegame version.
Definition: saveload.h:703
FileWriter::FileWriter
FileWriter(FILE *file)
Create the file writer, so it writes to a specific file.
Definition: saveload.cpp:2217
SlIsObjectValidInSavegame
static bool SlIsObjectValidInSavegame(const SaveLoad &sld)
Are we going to save this object or not?
Definition: saveload.cpp:1431
LZMASaveFilter::lzma
lzma_stream lzma
Stream state that we are writing to.
Definition: saveload.cpp:2555
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3204
LZO_BUFFER_SIZE
static const uint LZO_BUFFER_SIZE
Buffer size for the LZO compressor.
Definition: saveload.cpp:2253
REF_ORDER
@ REF_ORDER
Load/save a reference to an order.
Definition: saveload.h:583
SaveLoadType
SaveLoadType
Type of data saved.
Definition: saveload.h:677
SlDeque
static void SlDeque(void *deque, VarType conv)
Save/load a std::deque.
Definition: saveload.cpp:1372
SlLoadChunk
static void SlLoadChunk(const ChunkHandler &ch)
Load a chunk of data (eg vehicles, stations, etc.)
Definition: saveload.cpp:1963
LoadCheckData::checkable
bool checkable
True if the savegame could be checked by SL_LOAD_CHECK. (Old savegames are not checkable....
Definition: fios.h:34
SLV_5
@ SLV_5
5.0 1429 5.1 1440 5.2 1525 0.3.6
Definition: saveload.h:43
SetSaveLoadError
void SetSaveLoadError(StringID str)
Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friend...
Definition: saveload.cpp:2758
ZlibLoadFilter::~ZlibLoadFilter
~ZlibLoadFilter()
Clean everything up.
Definition: saveload.cpp:2399
Pool::PoolItem<&_orderlist_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:339
LoadCheckData::error_msg
std::string error_msg
Data to pass to SetDParamStr when displaying error.
Definition: fios.h:36
SAVE_DIR
@ SAVE_DIR
Base directory for all savegames.
Definition: fileio_type.h:110
LZMASaveFilter::LZMASaveFilter
LZMASaveFilter(std::shared_ptr< SaveFilter > chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2563
TimerGameTick::counter
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Definition: timer_game_tick.h:33
SaveLoadFormat::min_compression
byte min_compression
the minimum compression level of this format
Definition: saveload.cpp:2628
SlArray
static void SlArray(void *array, size_t length, VarType conv)
Save/Load the length of the array followed by the array of SL_VAR elements.
Definition: saveload.cpp:1057
SGT_OTTD
@ SGT_OTTD
OTTD savegame.
Definition: saveload.h:410
SVS_ALLOW_NEWLINE
@ SVS_ALLOW_NEWLINE
Allow newlines; replaces '\r ' with ' ' during processing.
Definition: string_type.h:47
LinkGraph
A connected component of a link graph.
Definition: linkgraph.h:37
_save_thread
static std::thread _save_thread
The thread we're using to compress and write a savegame.
Definition: saveload.cpp:372
SLE_VAR_STR
@ SLE_VAR_STR
string pointer
Definition: saveload.h:636
NoCompLoadFilter
Filter without any compression.
Definition: saveload.cpp:2343
_sl_minor_version
byte _sl_minor_version
the minor savegame version, DO NOT USE!
Definition: saveload.cpp:64
LZMALoadFilter::fread_buf
byte fread_buf[MEMORY_CHUNK_SIZE]
Buffer for reading from the file.
Definition: saveload.cpp:2513
SLA_SAVE
@ SLA_SAVE
saving
Definition: saveload.cpp:71
RemapOldStringID
StringID RemapOldStringID(StringID s)
Remap a string ID from the old format to the new format.
Definition: strings_sl.cpp:30
CSleep
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:24
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
Definition: error_gui.cpp:367
SaveLoadTable
std::span< const struct SaveLoad > SaveLoadTable
A table of SaveLoad entries.
Definition: saveload.h:497
REF_TOWN
@ REF_TOWN
Load/save a reference to a town.
Definition: saveload.h:586
DoExitSave
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:3161
SaveLoadFormat::init_write
std::shared_ptr< SaveFilter >(* init_write)(std::shared_ptr< SaveFilter > chain, byte compression)
Constructor for the save filter.
Definition: saveload.cpp:2626
ClearGRFConfigList
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
Definition: newgrf_config.cpp:356
GLAT_LOAD
@ GLAT_LOAD
Game loaded.
Definition: gamelog.h:18
REF_ROADSTOPS
@ REF_ROADSTOPS
Load/save a reference to a bus/truck stop.
Definition: saveload.h:588
FileToSaveLoad::title
std::string title
Internal name of the game.
Definition: saveload.h:398
SLE_FILE_END
@ SLE_FILE_END
Used to mark end-of-header in tables.
Definition: saveload.h:608
FileReader::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2192
_gamelog
Gamelog _gamelog
Gamelog instance.
Definition: gamelog.cpp:31
Station
Station data structure.
Definition: station_base.h:442
SlSkipArray
void SlSkipArray()
Skip an array or sparse array.
Definition: saveload.cpp:698
LinkGraphJob
Class for calculation jobs to be run on link graphs.
Definition: linkgraphjob.h:29
SaveOrLoad
SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
Definition: saveload.cpp:3052
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
SL_MIN_VERSION
@ SL_MIN_VERSION
First savegame version.
Definition: saveload.h:31
SaveLoadOperation
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:47
SlCopy
void SlCopy(void *object, size_t length, VarType conv)
Copy a list of SL_VARs to/from a savegame.
Definition: saveload.cpp:1027
NoCompLoadFilter::NoCompLoadFilter
NoCompLoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
Definition: saveload.cpp:2350
_ttdp_version
uint32_t _ttdp_version
version of TTDP savegame (if applicable)
Definition: saveload.cpp:62
FileToSaveLoad::name
std::string name
Name of the file.
Definition: saveload.h:397
FileReader::begin
long begin
The begin of the file.
Definition: saveload.cpp:2172
GB
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
_load_check_data
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition: fios_gui.cpp:40
AfterLoadGame
bool AfterLoadGame()
Perform a (large) amount of savegame conversion magic in order to load older savegames and to fill th...
Definition: afterload.cpp:564
SLF_ALLOW_NEWLINE
@ SLF_ALLOW_NEWLINE
Allow new lines in the strings.
Definition: saveload.h:671
SlErrorCorrupt
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition: saveload.cpp:364
SlSaveChunks
static void SlSaveChunks()
Save all chunks.
Definition: saveload.cpp:2103
SLA_LOAD_CHECK
@ SLA_LOAD_CHECK
partial loading into _load_check_data
Definition: saveload.cpp:74
SLV_END_PATCHPACKS
@ SLV_END_PATCHPACKS
286 Last known patchpack to use a version just above ours.
Definition: saveload.h:322
SLO_CHECK
@ SLO_CHECK
Load file for checking and/or preview.
Definition: fileio_type.h:48
SaveLoadParams::extra_msg
std::string extra_msg
the error message
Definition: saveload.cpp:208
LZMASaveFilter::fwrite_buf
byte fwrite_buf[MEMORY_CHUNK_SIZE]
Buffer for writing to the file.
Definition: saveload.cpp:2556
MemoryDumper::MemoryDumper
MemoryDumper()
Initialise our variables.
Definition: saveload.cpp:134
FixSCCEncoded
static void FixSCCEncoded(std::string &str)
Scan the string for old values of SCC_ENCODED and fix it to it's new, value.
Definition: saveload.cpp:912
StrMakeValid
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
Definition: string.cpp:114
_do_autosave
bool _do_autosave
are we doing an autosave at the moment?
Definition: saveload.cpp:66
MemoryDumper::GetSize
size_t GetSize() const
Get the size of the memory dump made so far.
Definition: saveload.cpp:184
DFT_GAME_FILE
@ DFT_GAME_FILE
Save game or scenario file.
Definition: fileio_type.h:31
FileToSaveLoad
Deals with the type of the savegame, independent of extension.
Definition: saveload.h:393
LoadCheckData::grfconfig
GRFConfig * grfconfig
NewGrf configuration from save.
Definition: fios.h:45
SaveLoadFormat::max_compression
byte max_compression
the maximum compression level of this format
Definition: saveload.cpp:2630
SLE_VAR_NULL
@ SLE_VAR_NULL
useful to write zeros in savegame.
Definition: saveload.h:635
LZOLoadFilter::Read
size_t Read(byte *buf, size_t ssize) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2266
SaveLoadHandler::GetLoadDescription
SaveLoadTable GetLoadDescription() const
Get the description for how to load the chunk.
Definition: saveload.cpp:3248
ChunkHandler::type
ChunkType type
Type of the chunk.
Definition: saveload.h:447
ReadBuffer
A buffer for reading (and buffering) savegame data.
Definition: saveload.cpp:87
TimerGameEconomy::date_fract
static DateFract date_fract
Fractional part of the day.
Definition: timer_game_economy.h:38
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:259
AUTOSAVE_DIR
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
Definition: fileio_type.h:111
SaveLoadCompatTable
std::span< const struct SaveLoadCompat > SaveLoadCompatTable
A table of SaveLoadCompat entries.
Definition: saveload.h:500
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:54
GetDetailedFileType
DetailedFileType GetDetailedFileType(FiosType fios_type)
Extract the detailed file type from a FiosType.
Definition: fileio_type.h:100
SlNullPointers
static void SlNullPointers()
Null all pointers (convert index -> nullptr)
Definition: saveload.cpp:309
SpecializedStation< Station, false >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index is a valid index for station of this type.
Definition: base_station_base.h:250
SaveFilter::chain
std::shared_ptr< SaveFilter > chain
Chained to the (savegame) filters.
Definition: saveload_filter.h:61
TimerGameEconomy::UsingWallclockUnits
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
Definition: timer_game_economy.cpp:97
Gamelog::Reset
void Reset()
Resets and frees all memory allocated - used before loading or starting a new game.
Definition: gamelog.cpp:94
SLA_LOAD
@ SLA_LOAD
loading
Definition: saveload.cpp:70
ZlibLoadFilter
Filter using Zlib compression.
Definition: saveload.cpp:2382
ChunkHandler
Handlers and description of chunk.
Definition: saveload.h:445
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:240
SaveLoad::conv
VarType conv
Type of the variable to be saved; this field combines both FileVarType and MemVarType.
Definition: saveload.h:700
LZMASaveFilter::WriteLoop
void WriteLoop(byte *p, size_t len, lzma_action action)
Helper loop for writing the data.
Definition: saveload.cpp:2580
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
SlCalcConvFileLen
static byte SlCalcConvFileLen(VarType conv)
Return the size in bytes of a certain type of normal/atomic variable as it appears in a saved game.
Definition: saveload.cpp:622
SaveLoadFormat::default_compression
byte default_compression
the default compression level of this format
Definition: saveload.cpp:2629
SaveLoadAction
SaveLoadAction
What are we currently doing?
Definition: saveload.cpp:69
SaveLoadHandler
Handler for saving/loading an object to/from disk.
Definition: saveload.h:503
SlCalcStdStringLen
static size_t SlCalcStdStringLen(const void *ptr)
Calculate the gross length of the string that it will occupy in the savegame.
Definition: saveload.cpp:896
NL_NONE
@ NL_NONE
not working in NeedLength mode
Definition: saveload.cpp:78
SLV_169
@ SLV_169
169 23816
Definition: saveload.h:245
AsyncSaveFinishProc
void(* AsyncSaveFinishProc)()
Callback for when the savegame loading is finished.
Definition: saveload.cpp:370
SlSetLength
void SlSetLength(size_t length)
Sets the length of either a RIFF object or the number of items in an array.
Definition: saveload.cpp:710
NoCompLoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2354
ZlibSaveFilter::z
z_stream z
Stream state we are writing to.
Definition: saveload.cpp:2427
ZlibLoadFilter::ZlibLoadFilter
ZlibLoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
Definition: saveload.cpp:2392
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
SlReadSimpleGamma
static uint SlReadSimpleGamma()
Read in the header descriptor of an object or an array.
Definition: saveload.cpp:465
SaveLoadFormat::init_load
std::shared_ptr< LoadFilter >(* init_load)(std::shared_ptr< LoadFilter > chain)
Constructor for the load filter.
Definition: saveload.cpp:2625
SLE_FILE_TYPE_MASK
@ SLE_FILE_TYPE_MASK
Mask to get the file-type (and not any flags).
Definition: saveload.h:622
saveload_filter.h
MemoryDumper::buf
byte * buf
Buffer we're going to write to.
Definition: saveload.cpp:130
ReadValue
int64_t ReadValue(const void *ptr, VarType conv)
Return a signed-long version of the value of a setting.
Definition: saveload.cpp:791
SlGlobList
void SlGlobList(const SaveLoadTable &slt)
Save or Load (a list of) global variables.
Definition: saveload.cpp:1906
NoCompSaveFilter
Filter without any compression.
Definition: saveload.cpp:2359
REF_STATION
@ REF_STATION
Load/save a reference to a station.
Definition: saveload.h:585
LZMALoadFilter
Filter without any compression.
Definition: saveload.cpp:2511
SLV_69
@ SLV_69
69 10319
Definition: saveload.h:125
SlCalcConvMemLen
static uint SlCalcConvMemLen(VarType conv)
Return the size in bytes of a certain type of normal/atomic variable as it appears in memory.
Definition: saveload.cpp:600
SaveLoadParams::lf
std::shared_ptr< LoadFilter > lf
Filter to read the savegame from.
Definition: saveload.cpp:205
AbstractFileType
AbstractFileType
The different abstract types of files that the system knows about.
Definition: fileio_type.h:16
ReferenceToInt
static size_t ReferenceToInt(const void *obj, SLRefType rt)
Pointers cannot be saved to a savegame, so this functions gets the index of the item,...
Definition: saveload.cpp:1103
SaveLoadFormat
The format for a reader/writer type of a savegame.
Definition: saveload.cpp:2619
FileToSaveLoad::abstract_ftype
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Definition: saveload.h:396
ReadBuffer::buf
byte buf[MEMORY_CHUNK_SIZE]
Buffer we're going to read from.
Definition: saveload.cpp:88
SaveLoadParams::block_mode
byte block_mode
???
Definition: saveload.cpp:194
FileWriter::file
FILE * file
The file to write to.
Definition: saveload.cpp:2211
SVS_ALLOW_CONTROL_CODE
@ SVS_ALLOW_CONTROL_CODE
Allow the special control codes.
Definition: string_type.h:48
BASE_DIR
@ BASE_DIR
Base directory for all subdirectories.
Definition: fileio_type.h:109
LoadFilter::LoadFilter
LoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
Definition: saveload_filter.h:22
SL_SAVEBYTE
@ SL_SAVEBYTE
Save (but not load) a byte.
Definition: saveload.h:690
GetVarMemType
constexpr VarType GetVarMemType(VarType type)
Get the NumberType of a setting.
Definition: saveload.h:732
SaveFileDone
static void SaveFileDone()
Update the gui accordingly when saving is done and release locks on saveload.
Definition: saveload.cpp:2745
SLF_ALLOW_CONTROL
@ SLF_ALLOW_CONTROL
Allow control codes in the strings.
Definition: saveload.h:670
SlSkipHandler
Handler that is assigned when there is a struct read in the savegame which is not known to the code.
Definition: saveload.cpp:1678
MemoryDumper::WriteByte
void WriteByte(byte b)
Write a single byte into the dumper.
Definition: saveload.cpp:149
SLE_FILE_HAS_LENGTH_FIELD
@ SLE_FILE_HAS_LENGTH_FIELD
Bit stored in savegame to indicate field has a length field for each entry.
Definition: saveload.h:623
SLO_LOAD
@ SLO_LOAD
File is being loaded.
Definition: fileio_type.h:49
SaveFileError
static void SaveFileError()
Show a gui message when saving has failed.
Definition: saveload.cpp:2775
IsGoodGRFConfigList
GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
Check if all GRFs in the GRF config from a savegame can be loaded.
Definition: newgrf_config.cpp:469
_sl_version
SaveLoadVersion _sl_version
the major savegame version identifier
Definition: saveload.cpp:63
SlFixPointers
static void SlFixPointers()
Fix all pointers (convert index -> pointer)
Definition: saveload.cpp:2156
BSWAP32
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:345
SavegameType
SavegameType
Types of save games.
Definition: saveload.h:406
SAVEGAME_VERSION
const SaveLoadVersion SAVEGAME_VERSION
Current savegame version of OpenTTD.
ZlibSaveFilter::ZlibSaveFilter
ZlibSaveFilter(std::shared_ptr< SaveFilter > chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2435
ZlibSaveFilter
Filter using Zlib compression.
Definition: saveload.cpp:2426
SLO_SAVE
@ SLO_SAVE
File is being saved.
Definition: fileio_type.h:50
SBI_SAVELOAD_FINISH
@ SBI_SAVELOAD_FINISH
finished saving
Definition: statusbar_gui.h:16
IntToReference
static void * IntToReference(size_t index, SLRefType rt)
Pointers cannot be loaded from a savegame, so this function gets the index from the savegame and retu...
Definition: saveload.cpp:1136
NeedLength
NeedLength
Definition: saveload.cpp:77
SlSaveLoadRef
void SlSaveLoadRef(void *ptr, VarType conv)
Handle conversion for references.
Definition: saveload.cpp:1212
CH_TYPE_MASK
@ CH_TYPE_MASK
All ChunkType values have to be within this mask.
Definition: saveload.h:440
NL_CALCLENGTH
@ NL_CALCLENGTH
need to calculate the length
Definition: saveload.cpp:80
ChunkHandler::Save
virtual void Save() const
Save the chunk.
Definition: saveload.h:457
CH_READONLY
@ CH_READONLY
Chunk is never saved.
Definition: saveload.h:441
SlCalcDequeLen
static size_t SlCalcDequeLen(const void *deque, VarType conv)
Return the size in bytes of a std::deque.
Definition: saveload.cpp:1351
SlWriteByte
void SlWriteByte(byte b)
Wrapper for writing a byte to the dumper.
Definition: saveload.cpp:414
IsSavegameVersionBefore
bool IsSavegameVersionBefore(SaveLoadVersion major, byte minor=0)
Checks whether the savegame is below major.
Definition: saveload.h:1215
SL_VAR
@ SL_VAR
Save/load a variable.
Definition: saveload.h:678
free
void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:379
_savegame_format
std::string _savegame_format
how to compress savegames
Definition: saveload.cpp:65
FioFOpenFile
FILE * FioFOpenFile(const std::string &filename, const char *mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition: fileio.cpp:263
SaveLoadParams::sf
std::shared_ptr< SaveFilter > sf
Filter to write the savegame to.
Definition: saveload.cpp:202
LZMASaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2600
NL_WANTLENGTH
@ NL_WANTLENGTH
writing length and data
Definition: saveload.cpp:79
GetSaveLoadErrorString
const char * GetSaveLoadErrorString()
Get the string representation of the error message.
Definition: saveload.cpp:2764
ZlibLoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2404
SanitizeFilename
void SanitizeFilename(std::string &filename)
Sanitizes a filename, i.e.
Definition: fileio.cpp:1088
SlCopyInternal
static void SlCopyInternal(void *object, size_t length, VarType conv)
Internal function to save/Load a list of SL_VARs.
Definition: saveload.cpp:978
PersistentStorage
Class for pooled persistent storage of data.
Definition: newgrf_storage.h:199
_savegame_type
SavegameType _savegame_type
type of savegame we are loading
Definition: saveload.cpp:59
SlLoadCheckChunks
static void SlLoadCheckChunks()
Load all chunks for savegame checking.
Definition: saveload.cpp:2141
MemoryDumper::Flush
void Flush(std::shared_ptr< SaveFilter > writer)
Flush this dumper into a writer.
Definition: saveload.cpp:165
CopyFromOldName
std::string CopyFromOldName(StringID id)
Copy and convert old custom names to UTF-8.
Definition: strings_sl.cpp:61
SlVector
static void SlVector(void *vector, VarType conv)
Save/load a std::vector.
Definition: saveload.cpp:1414
FileReader::file
FILE * file
The file to read from.
Definition: saveload.cpp:2171
SL_REINIT
@ SL_REINIT
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
Definition: saveload.h:389
SaveLoad::cmd
SaveLoadType cmd
The action to take with the saved/loaded type, All types need different action.
Definition: saveload.h:699
FiosItem
Deals with finding savegames.
Definition: fios.h:79
ReadBuffer::ReadBuffer
ReadBuffer(std::shared_ptr< LoadFilter > reader)
Initialise our variables.
Definition: saveload.cpp:98
SLRefType
SLRefType
Type of reference (SLE_REF, SLE_CONDREF).
Definition: saveload.h:582
StartNewThread
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:47
SlSaveLoadConv
static void SlSaveLoadConv(void *ptr, VarType conv)
Handle all conversion and typechecking of variables here.
Definition: saveload.cpp:841
ZlibSaveFilter::WriteLoop
void WriteLoop(byte *p, size_t len, int mode)
Helper loop for writing the data.
Definition: saveload.cpp:2453
FileWriter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2227
GetVariableAddress
void * GetVariableAddress(const void *object, const SaveLoad &sld)
Get the address of the variable.
Definition: saveload.h:1253
GameSessionStats::savegame_size
std::optional< size_t > savegame_size
Size of the last saved savegame in bytes, or std::nullopt if not saved yet.
Definition: openttd.h:58
GetSavegameFormat
static const SaveLoadFormat * GetSavegameFormat(const std::string &full_name, byte *compression_level)
Return the savegameformat of the game.
Definition: saveload.cpp:2668
NoCompSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2368
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:50
SaveFileToDisk
static SaveOrLoadResult SaveFileToDisk(bool threaded)
We have written the whole game into memory, _memory_savegame, now find and appropriate compressor and...
Definition: saveload.cpp:2786
SaveLoadFormat::name
const char * name
name of the compressor/decompressor (debug-only)
Definition: saveload.cpp:2622
SlCalcRefListLen
static size_t SlCalcRefListLen(const void *list, VarType conv)
Return the size in bytes of a list.
Definition: saveload.cpp:1324
GenerateDefaultSaveName
std::string GenerateDefaultSaveName()
Get the default name for a savegame or screenshot.
Definition: saveload.cpp:3169
GUISettings::keep_all_autosave
bool keep_all_autosave
name the autosave in a different way
Definition: settings_type.h:162
ChunkHandlers
static const std::vector< ChunkHandlerRef > & ChunkHandlers()
Definition: saveload.cpp:215
SLV_SAVELOAD_LIST_LENGTH
@ SLV_SAVELOAD_LIST_LENGTH
293 PR#9374 Consistency in list length with SL_STRUCT / SL_STRUCTLIST / SL_DEQUE / SL_REFLIST.
Definition: saveload.h:331
SL_ARR
@ SL_ARR
Save/load a fixed-size array of SL_VAR elements.
Definition: saveload.h:684
SLE_FILE_STRINGID
@ SLE_FILE_STRINGID
StringID offset into strings-array.
Definition: saveload.h:617
REF_STORAGE
@ REF_STORAGE
Load/save a reference to a persistent storage.
Definition: saveload.h:592
SCENARIO_DIR
@ SCENARIO_DIR
Base directory for all scenarios.
Definition: fileio_type.h:112
FT_INVALID
@ FT_INVALID
Invalid or unknown file type.
Definition: fileio_type.h:22
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
SLA_PTRS
@ SLA_PTRS
fixing pointers
Definition: saveload.cpp:72
SL_MAX_VERSION
@ SL_MAX_VERSION
Highest possible saveload version.
Definition: saveload.h:382
SaveFileStart
static void SaveFileStart()
Update the gui accordingly when starting saving and set locks on saveload.
Definition: saveload.cpp:2736
REF_ENGINE_RENEWS
@ REF_ENGINE_RENEWS
Load/save a reference to an engine renewal (autoreplace).
Definition: saveload.h:589
DFT_OLD_GAME_FILE
@ DFT_OLD_GAME_FILE
Old save game or scenario file.
Definition: fileio_type.h:30
ReadBuffer::reader
std::shared_ptr< LoadFilter > reader
The filter used to actually read.
Definition: saveload.cpp:91
REF_VEHICLE
@ REF_VEHICLE
Load/save a reference to a vehicle.
Definition: saveload.h:584
SL_REF
@ SL_REF
Save/load a reference.
Definition: saveload.h:679
SLV_4
@ SLV_4
4.0 1 4.1 122 0.3.3, 0.3.4 4.2 1222 0.3.5 4.3 1417 4.4 1426
Definition: saveload.h:37
DoAutoOrNetsave
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
Definition: saveload.cpp:3143
REF_CARGO_PACKET
@ REF_CARGO_PACKET
Load/save a reference to a cargo packet.
Definition: saveload.h:590
SL_STRUCT
@ SL_STRUCT
Save/load a struct.
Definition: saveload.h:680
SBI_SAVELOAD_START
@ SBI_SAVELOAD_START
started saving
Definition: statusbar_gui.h:15
LZMALoadFilter::lzma
lzma_stream lzma
Stream state that we are reading from.
Definition: saveload.cpp:2512
ReadBuffer::bufp
byte * bufp
Location we're at reading the buffer.
Definition: saveload.cpp:89
SlAutolength
void SlAutolength(AutolengthProc *proc, void *arg)
Do something of which I have no idea what it is :P.
Definition: saveload.cpp:1916
EngineRenew
Struct to store engine replacements.
Definition: autoreplace_base.h:33
REF_VEHICLE_OLD
@ REF_VEHICLE_OLD
Load/save an old-style reference to a vehicle (for pre-4.4 savegames).
Definition: saveload.h:587
LZOLoadFilter::LZOLoadFilter
LZOLoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
Definition: saveload.cpp:2261
SaveLoadParams::error_str
StringID error_str
the translatable error message to show
Definition: saveload.cpp:207
ChunkHandler::Load
virtual void Load() const =0
Load the chunk.
_game_session_stats
GameSessionStats _game_session_stats
Statistics about the current session.
Definition: gfx.cpp:50
ZlibSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2481
SlSkipHandler::GetDescription
virtual SaveLoadTable GetDescription() const override
Get the description of the fields in the savegame.
Definition: saveload.cpp:1697
StringValidationSettings
StringValidationSettings
Settings for the string validation.
Definition: string_type.h:44
SlGetStructListLength
size_t SlGetStructListLength(size_t limit)
Get the length of this list; if it exceeds the limit, error out.
Definition: saveload.cpp:1648
SaveLoad::handler
std::shared_ptr< SaveLoadHandler > handler
Custom handler for Save/Load procs.
Definition: saveload.h:707
LoadCheckData::error
StringID error
Error message from loading. INVALID_STRING_ID if no error.
Definition: fios.h:35
SL_VECTOR
@ SL_VECTOR
Save/load a vector of SL_VAR elements.
Definition: saveload.h:686
SlCalcVectorLen
static size_t SlCalcVectorLen(const void *vector, VarType conv)
Return the size in bytes of a std::vector.
Definition: saveload.cpp:1393
MemoryDumper::bufe
byte * bufe
End of the buffer we write to.
Definition: saveload.cpp:131
SaveLoadParams::expect_table_header
bool expect_table_header
In the case of a table, if the header is saved/loaded.
Definition: saveload.cpp:199
SlLoadCheckChunk
static void SlLoadCheckChunk(const ChunkHandler &ch)
Load a chunk of data for checking savegames.
Definition: saveload.cpp:2016
LoadFilter::chain
std::shared_ptr< LoadFilter > chain
Chained to the (savegame) filters.
Definition: saveload_filter.h:16
REF_LINK_GRAPH_JOB
@ REF_LINK_GRAPH_JOB
Load/save a reference to a link graph job.
Definition: saveload.h:594
ZlibLoadFilter::z
z_stream z
Stream state we are reading from.
Definition: saveload.cpp:2385
LZMALoadFilter::~LZMALoadFilter
~LZMALoadFilter()
Clean everything up.
Definition: saveload.cpp:2526
DFT_INVALID
@ DFT_INVALID
Unknown or invalid file.
Definition: fileio_type.h:43
_sl
static SaveLoadParams _sl
Parameters used for/at saveload.
Definition: saveload.cpp:213
Gamelog::StartAction
void StartAction(GamelogActionType at)
Stores information about new action, but doesn't allocate it Action is allocated only when there is a...
Definition: gamelog.cpp:65
Gamelog::StopAction
void StopAction()
Stops logging of any changes.
Definition: gamelog.cpp:74
SaveLoadParams::need_length
NeedLength need_length
working in NeedLength (Autolength) mode?
Definition: saveload.cpp:193
Utf8EncodedCharLen
int8_t Utf8EncodedCharLen(char c)
Return the length of an UTF-8 encoded value based on a single char.
Definition: string_func.h:123
Pool::PoolItem<&_company_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:388
SaveWithFilter
SaveOrLoadResult SaveWithFilter(std::shared_ptr< SaveFilter > writer, bool threaded)
Save the game using a (writer) filter.
Definition: saveload.cpp:2876
SlStorageHelper::SlCalcLen
static size_t SlCalcLen(const void *storage, VarType conv, SaveLoadType cmd=SL_VAR)
Internal templated helper to return the size in bytes of a list-like type.
Definition: saveload.cpp:1245
GetSavegameFileType
static uint8_t GetSavegameFileType(const SaveLoad &sld)
Return the type as saved/loaded inside the savegame.
Definition: saveload.cpp:565
GUISettings::threaded_saves
bool threaded_saves
should we do threaded saves?
Definition: settings_type.h:161
FT_NONE
@ FT_NONE
nothing to do
Definition: fileio_type.h:17
FiosNumberedSaveName
A savegame name automatically numbered.
Definition: fios.h:129
REF_ORDERLIST
@ REF_ORDERLIST
Load/save a reference to an orderlist.
Definition: saveload.h:591
SaveLoadParams
The saveload struct, containing reader-writer functions, buffer, version, etc.
Definition: saveload.cpp:191
LZMALoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2531
SlGetFieldLength
size_t SlGetFieldLength()
Get the length of the current object.
Definition: saveload.cpp:779
SlCalcArrayLen
static size_t SlCalcArrayLen(size_t length, VarType conv)
Return the size in bytes of a certain type of atomic array.
Definition: saveload.cpp:1046
DetailedFileType
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:28
LoadCheckData::Clear
void Clear()
Reset read data.
Definition: fios_gui.cpp:48
SlStorageHelper
Template class to help with list-like types.
Definition: saveload.cpp:1236
ZlibSaveFilter::fwrite_buf
byte fwrite_buf[MEMORY_CHUNK_SIZE]
Buffer for writing to the file.
Definition: saveload.cpp:2428
_saveload_formats
static const SaveLoadFormat _saveload_formats[]
The different saveload formats known/understood by OpenTTD.
Definition: saveload.cpp:2632
SLV_START_PATCHPACKS
@ SLV_START_PATCHPACKS
220 First known patchpack to use a version just above ours.
Definition: saveload.h:321
FileReader::Reset
void Reset() override
Reset this filter to read from the beginning of the file.
Definition: saveload.cpp:2200
SL_REFLIST
@ SL_REFLIST
Save/load a list of SL_REF elements.
Definition: saveload.h:687
FileToSaveLoad::Set
void Set(const FiosItem &item)
Set the title of the file.
Definition: saveload.cpp:3241
GUISettings::date_format_in_default_names
uint8_t date_format_in_default_names
should the default savegame/screenshot name use long dates (31th Dec 2008), short dates (31-12-2008) ...
Definition: settings_type.h:165
SaveFilter
Interface for filtering a savegame till it is written.
Definition: saveload_filter.h:59
SetAsyncSaveFinish
static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
Called by save thread to tell we finished saving.
Definition: saveload.cpp:378
SetDParam
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings.cpp:104
SaveLoadParams::action
SaveLoadAction action
are we doing a save or a load atm.
Definition: saveload.cpp:192
endof
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:308
_file_to_saveload
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:60
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition: order_base.h:260
SlGetGammaLength
static uint SlGetGammaLength(size_t i)
Return how many bytes used to encode a gamma value.
Definition: saveload.cpp:532
SlReadByte
byte SlReadByte()
Wrapper for reading a byte from the buffer.
Definition: saveload.cpp:405
ZlibSaveFilter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: saveload.cpp:2486
SaveLoadParams::dumper
std::unique_ptr< MemoryDumper > dumper
Memory dumper to write the savegame to.
Definition: saveload.cpp:201
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition: strings.cpp:327
LZOSaveFilter
Filter using LZO compression.
Definition: saveload.cpp:2303
ChunkHandlerTable
std::span< const ChunkHandlerRef > ChunkHandlerTable
A table of ChunkHandler entries.
Definition: saveload.h:494
SaveLoadParams::obj_len
size_t obj_len
the length of the current object we are busy with
Definition: saveload.cpp:197
LZMASaveFilter::~LZMASaveFilter
~LZMASaveFilter()
Clean up what we allocated.
Definition: saveload.cpp:2569
SlSkipBytes
void SlSkipBytes(size_t length)
Read in bytes from the file/data structure but don't do anything with them, discarding them in effect...
Definition: saveload.h:1297
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
SetDParamStr
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:352
SaveLoadFormat::tag
uint32_t tag
the 4-letter tag by which it is identified in the savegame
Definition: saveload.cpp:2623
SlWriteSimpleGamma
static void SlWriteSimpleGamma(size_t i)
Write the header descriptor of an object or an array.
Definition: saveload.cpp:507
NoCompSaveFilter::NoCompSaveFilter
NoCompSaveFilter(std::shared_ptr< SaveFilter > chain, byte)
Initialise this filter.
Definition: saveload.cpp:2364
SaveLoad::version_from
SaveLoadVersion version_from
Save/load the variable starting from this savegame version.
Definition: saveload.h:702
LoadCheckData::grf_compatibility
GRFListCompatibility grf_compatibility
Summary state of NewGrfs, whether missing files or only compatible found.
Definition: fios.h:46
SaveOrLoadResult
SaveOrLoadResult
Save or load result codes.
Definition: saveload.h:386
WL_ERROR
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition: error.h:26
FiosType
FiosType
Elements of a file system that are recognized.
Definition: fileio_type.h:67
SLE_VAR_STRQ
@ SLE_VAR_STRQ
string pointer enclosed in quotes
Definition: saveload.h:637
SaveLoadParams::saveinprogress
bool saveinprogress
Whether there is currently a save in progress.
Definition: saveload.cpp:210
SaveLoadParams::reader
std::unique_ptr< ReadBuffer > reader
Savegame reading buffer.
Definition: saveload.cpp:204
Ticks::TICKS_PER_SECOND
static constexpr TimerGameTick::Ticks TICKS_PER_SECOND
Estimation of how many ticks fit in a single second.
Definition: timer_game_tick.h:49
SlRefList
static void SlRefList(void *list, VarType conv)
Save/Load a list.
Definition: saveload.cpp:1334
ReadBuffer::read
size_t read
The amount of read bytes so far from the filter.
Definition: saveload.cpp:92
_grfconfig
GRFConfig * _grfconfig
First item in list of current GRF set up.
Definition: newgrf_config.cpp:164
REF_LINK_GRAPH
@ REF_LINK_GRAPH
Load/save a reference to a link graph.
Definition: saveload.h:593
saveload_internal.h
SLO_INVALID
@ SLO_INVALID
Unknown file operation.
Definition: fileio_type.h:52
SLA_NULL
@ SLA_NULL
null all pointers (on loading error)
Definition: saveload.cpp:73
SlStdString
static void SlStdString(void *ptr, VarType conv)
Save/Load a std::string.
Definition: saveload.cpp:930
LoadFilter
Interface for filtering a savegame till it is loaded.
Definition: saveload_filter.h:14
Town
Town data structure.
Definition: town.h:50
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:300
SaveLoadParams::error
bool error
did an error occur or not
Definition: saveload.cpp:195
CargoPacket
Container for cargo from the same location and time.
Definition: cargopacket.h:40
SL_DEQUE
@ SL_DEQUE
Save/load a deque of SL_VAR elements.
Definition: saveload.h:685
LoadWithFilter
SaveOrLoadResult LoadWithFilter(std::shared_ptr< LoadFilter > reader)
Load the game using a (reader) filter.
Definition: saveload.cpp:3032
ChunkHandler::id
uint32_t id
Unique ID (4 letters).
Definition: saveload.h:446
FileReader::~FileReader
~FileReader()
Make sure everything is cleaned up.
Definition: saveload.cpp:2183
SlError
void SlError(StringID string, const std::string &extra_msg)
Error handler.
Definition: saveload.cpp:334
GetAbstractFileType
AbstractFileType GetAbstractFileType(FiosType fios_type)
Extract the abstract file type from a FiosType.
Definition: fileio_type.h:90
SlCompatTableHeader
std::vector< SaveLoad > SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
Load a table header in a savegame compatible way.
Definition: saveload.cpp:1852
SlCopyBytes
static void SlCopyBytes(void *ptr, size_t length)
Save/Load bytes.
Definition: saveload.cpp:762
LZOLoadFilter
Filter using LZO compression.
Definition: saveload.cpp:2256
MEMORY_CHUNK_SIZE
static const size_t MEMORY_CHUNK_SIZE
Save in chunks of 128 KiB.
Definition: saveload.cpp:84
ProcessAsyncSaveFinish
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition: saveload.cpp:389
MemoryDumper::blocks
std::vector< byte * > blocks
Buffer with blocks of allocated memory.
Definition: saveload.cpp:129
FileReader
Yes, simply reading from a file.
Definition: saveload.cpp:2170
SaveLoadParams::last_array_index
int last_array_index
in the case of an array, the current and last positions
Definition: saveload.cpp:198
SlCalcRefLen
static size_t SlCalcRefLen()
Return the size in bytes of a reference (pointer)
Definition: saveload.cpp:639
LZMASaveFilter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: saveload.cpp:2605
Utf8Encode
size_t Utf8Encode(T buf, char32_t c)
Encode a unicode character and place it in the buffer.
Definition: string.cpp:479
_async_save_finish
static std::atomic< AsyncSaveFinishProc > _async_save_finish
Callback to call when the savegame loading is finished.
Definition: saveload.cpp:371
SL_ERROR
@ SL_ERROR
error that was caught before internal structures were modified
Definition: saveload.h:388
FileToSaveLoad::detail_ftype
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
Definition: saveload.h:395
Pool::PoolItem<&_orderlist_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:328
SaveLoad::length
uint16_t length
(Conditional) length of the variable (eg. arrays) (max array size is 65536 elements).
Definition: saveload.h:701
WC_STATUS_BAR
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
Definition: window_type.h:64
ReadBuffer::GetSize
size_t GetSize() const
Get the size of the memory dump made so far.
Definition: saveload.cpp:120
RoadStop
A Stop for a Road Vehicle.
Definition: roadstop_base.h:22
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
FiosNumberedSaveName::Extension
std::string Extension()
Generate an extension for a savegame name.
Definition: fios.cpp:772
SaveLoad::name
std::string name
Name of this field (optional, used for tables).
Definition: saveload.h:698
SlObject
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
Definition: saveload.cpp:1661
ZlibSaveFilter::~ZlibSaveFilter
~ZlibSaveFilter()
Clean up what we allocated.
Definition: saveload.cpp:2442
ChunkHandler::LoadCheck
virtual void LoadCheck(size_t len=0) const
Load the chunk for game preview.
Definition: saveload.cpp:1940
Utf8Decode
size_t Utf8Decode(char32_t *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:438
LZMASaveFilter
Filter using LZMA compression.
Definition: saveload.cpp:2554
SlTableHeader
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
Definition: saveload.cpp:1714
SlSetStructListLength
void SlSetStructListLength(size_t length)
Set the length of this list.
Definition: saveload.cpp:1632
FileToSaveLoad::SetMode
void SetMode(FiosType ft)
Set the mode and file type of the file to save or load based on the type of file entry at the file sy...
Definition: saveload.cpp:3212
SlSkipHandler::GetCompatDescription
virtual SaveLoadCompatTable GetCompatDescription() const override
Get the pre-header description of the fields in the savegame.
Definition: saveload.cpp:1702
SaveLoad
SaveLoad type struct.
Definition: saveload.h:697
Company
Definition: company_base.h:129
LZOSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2313
ClearSaveLoadState
static void ClearSaveLoadState()
Clear/free saveload state.
Definition: saveload.cpp:2727
DoSave
static SaveOrLoadResult DoSave(std::shared_ptr< SaveFilter > writer, bool threaded)
Actually perform the saving of the savegame.
Definition: saveload.cpp:2844
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:316
SL_OK
@ SL_OK
completed successfully
Definition: saveload.h:387
SVS_REPLACE_WITH_QUESTION_MARK
@ SVS_REPLACE_WITH_QUESTION_MARK
Replace the unknown/bad bits with question marks.
Definition: string_type.h:46
FiosNumberedSaveName::Filename
std::string Filename()
Generate a savegame name and number according to _settings_client.gui.max_num_autosaves.
Definition: fios.cpp:762
SL_STDSTR
@ SL_STDSTR
Save/load a std::string.
Definition: saveload.h:682
Order
Definition: order_base.h:36
LZOSaveFilter::LZOSaveFilter
LZOSaveFilter(std::shared_ptr< SaveFilter > chain, byte)
Initialise this filter.
Definition: saveload.cpp:2308
_lzma_init
static const lzma_stream _lzma_init
Have a copy of an initialised LZMA stream.
Definition: saveload.cpp:2508
SLE_VAR_NAME
@ SLE_VAR_NAME
old custom name to be converted to a char pointer
Definition: saveload.h:638
LZMALoadFilter::LZMALoadFilter
LZMALoadFilter(std::shared_ptr< LoadFilter > chain)
Initialise this filter.
Definition: saveload.cpp:2519
FileWriter::~FileWriter
~FileWriter()
Make sure everything is cleaned up.
Definition: saveload.cpp:2222
SlCalcObjLength
size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt)
Calculate the size of an object.
Definition: saveload.cpp:1470
SlIterateArray
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition: saveload.cpp:656
WriteValue
void WriteValue(void *ptr, VarType conv, int64_t val)
Write the value of a setting.
Definition: saveload.cpp:815
FileReader::FileReader
FileReader(FILE *file)
Create the file reader, so it reads from a specific file.
Definition: saveload.cpp:2178
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
SlSaveChunk
static void SlSaveChunk(const ChunkHandler &ch)
Save a chunk of data (eg.
Definition: saveload.cpp:2067
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:635
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:27
SlFindChunkHandler
static const ChunkHandler * SlFindChunkHandler(uint32_t id)
Find the ChunkHandler that will be used for processing the found chunk in the savegame or in memory.
Definition: saveload.cpp:2119
FileWriter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: saveload.cpp:2235
FileToSaveLoad::file_op
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:394
FileWriter
Yes, simply writing to a file.
Definition: saveload.cpp:2210
ReadBuffer::bufe
byte * bufe
End of the buffer we can read from.
Definition: saveload.cpp:90
GetVarFileType
constexpr VarType GetVarFileType(VarType type)
Get the FileType of a setting.
Definition: saveload.h:743
MemoryDumper
Container for dumping the savegame (quickly) to memory.
Definition: saveload.cpp:128
SL_STRUCTLIST
@ SL_STRUCTLIST
Save/load a list of structs.
Definition: saveload.h:688
DoLoad
static SaveOrLoadResult DoLoad(std::shared_ptr< LoadFilter > reader, bool load_check)
Actually perform the loading of a "non-old" savegame.
Definition: saveload.cpp:2893
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition: timer_game_economy.h:37
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103