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

OpenTTD Source 13.1

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 "../date_func.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 #include <deque>
47 #include <vector>
48 #include <string>
49 #ifdef __EMSCRIPTEN__
50 # include <emscripten.h>
51 #endif
52
53 #include "table/strings.h"
54
55 #include "saveload_internal.h"
56 #include "saveload_filter.h"
57
58 #include "../safeguards.h"
59
60 extern const SaveLoadVersion SAVEGAME_VERSION = (SaveLoadVersion)(SL_MAX_VERSION - 1);
61
62 SavegameType _savegame_type;
63 FileToSaveLoad _file_to_saveload;
64
65 uint32 _ttdp_version;
66 SaveLoadVersion _sl_version;
67 byte _sl_minor_version;
68 std::string _savegame_format;
69 bool _do_autosave;
70
72 enum SaveLoadAction {
73 SLA_LOAD,
74 SLA_SAVE,
75 SLA_PTRS,
76 SLA_NULL,
77 SLA_LOAD_CHECK,
78 };
79
80 enum NeedLength {
81 NL_NONE = 0,
82 NL_WANTLENGTH = 1,
83 NL_CALCLENGTH = 2,
84 };
85
87 static const size_t MEMORY_CHUNK_SIZE = 128 * 1024;
88
90 struct ReadBuffer {
91 byte buf[MEMORY_CHUNK_SIZE];
92 byte *bufp;
93 byte *bufe;
94 LoadFilter *reader;
95 size_t read;
96
101 ReadBuffer(LoadFilter *reader) : bufp(nullptr), bufe(nullptr), reader(reader), read(0)
102 {
103 }
104
105 inline byte ReadByte()
106 {
107 if (this->bufp == this->bufe) {
108 size_t len = this->reader->Read(this->buf, lengthof(this->buf));
109 if (len == 0) SlErrorCorrupt("Unexpected end of chunk");
110
111 this->read += len;
112 this->bufp = this->buf;
113 this->bufe = this->buf + len;
114 }
115
116 return *this->bufp++;
117 }
118
123 size_t GetSize() const
124 {
125 return this->read - (this->bufe - this->bufp);
126 }
127 };
128
129
131 struct MemoryDumper {
132 std::vector<byte *> blocks;
133 byte *buf;
134 byte *bufe;
135
137 MemoryDumper() : buf(nullptr), bufe(nullptr)
138 {
139 }
140
141 ~MemoryDumper()
142 {
143 for (auto p : this->blocks) {
144 free(p);
145 }
146 }
147
152 inline void WriteByte(byte b)
153 {
154 /* Are we at the end of this chunk? */
155 if (this->buf == this->bufe) {
156 this->buf = CallocT<byte>(MEMORY_CHUNK_SIZE);
157 this->blocks.push_back(this->buf);
158 this->bufe = this->buf + MEMORY_CHUNK_SIZE;
159 }
160
161 *this->buf++ = b;
162 }
163
168 void Flush(SaveFilter *writer)
169 {
170 uint i = 0;
171 size_t t = this->GetSize();
172
173 while (t > 0) {
174 size_t to_write = std::min(MEMORY_CHUNK_SIZE, t);
175
176 writer->Write(this->blocks[i++], to_write);
177 t -= to_write;
178 }
179
180 writer->Finish();
181 }
182
187 size_t GetSize() const
188 {
189 return this->blocks.size() * MEMORY_CHUNK_SIZE - (this->bufe - this->buf);
190 }
191 };
192
194 struct SaveLoadParams {
195 SaveLoadAction action;
196 NeedLength need_length;
197 byte block_mode;
198 bool error;
199
200 size_t obj_len;
201 int array_index, last_array_index;
202 bool expect_table_header;
203
204 MemoryDumper *dumper;
205 SaveFilter *sf;
206
207 ReadBuffer *reader;
208 LoadFilter *lf;
209
210 StringID error_str;
211 char *extra_msg;
212
213 bool saveinprogress;
214 };
215
216 static SaveLoadParams _sl;
217
218 static const std::vector<ChunkHandlerRef> &ChunkHandlers()
219 {
220 /* These define the chunks */
221 extern const ChunkHandlerTable _gamelog_chunk_handlers;
222 extern const ChunkHandlerTable _map_chunk_handlers;
223 extern const ChunkHandlerTable _misc_chunk_handlers;
224 extern const ChunkHandlerTable _name_chunk_handlers;
225 extern const ChunkHandlerTable _cheat_chunk_handlers;
226 extern const ChunkHandlerTable _setting_chunk_handlers;
227 extern const ChunkHandlerTable _company_chunk_handlers;
228 extern const ChunkHandlerTable _engine_chunk_handlers;
229 extern const ChunkHandlerTable _veh_chunk_handlers;
230 extern const ChunkHandlerTable _waypoint_chunk_handlers;
231 extern const ChunkHandlerTable _depot_chunk_handlers;
232 extern const ChunkHandlerTable _order_chunk_handlers;
233 extern const ChunkHandlerTable _town_chunk_handlers;
234 extern const ChunkHandlerTable _sign_chunk_handlers;
235 extern const ChunkHandlerTable _station_chunk_handlers;
236 extern const ChunkHandlerTable _industry_chunk_handlers;
237 extern const ChunkHandlerTable _economy_chunk_handlers;
238 extern const ChunkHandlerTable _subsidy_chunk_handlers;
239 extern const ChunkHandlerTable _cargomonitor_chunk_handlers;
240 extern const ChunkHandlerTable _goal_chunk_handlers;
241 extern const ChunkHandlerTable _story_page_chunk_handlers;
242 extern const ChunkHandlerTable _league_chunk_handlers;
243 extern const ChunkHandlerTable _ai_chunk_handlers;
244 extern const ChunkHandlerTable _game_chunk_handlers;
245 extern const ChunkHandlerTable _animated_tile_chunk_handlers;
246 extern const ChunkHandlerTable _newgrf_chunk_handlers;
247 extern const ChunkHandlerTable _group_chunk_handlers;
248 extern const ChunkHandlerTable _cargopacket_chunk_handlers;
249 extern const ChunkHandlerTable _autoreplace_chunk_handlers;
250 extern const ChunkHandlerTable _labelmaps_chunk_handlers;
251 extern const ChunkHandlerTable _linkgraph_chunk_handlers;
252 extern const ChunkHandlerTable _airport_chunk_handlers;
253 extern const ChunkHandlerTable _object_chunk_handlers;
254 extern const ChunkHandlerTable _persistent_storage_chunk_handlers;
255
257 static const ChunkHandlerTable _chunk_handler_tables[] = {
258 _gamelog_chunk_handlers,
259 _map_chunk_handlers,
260 _misc_chunk_handlers,
261 _name_chunk_handlers,
262 _cheat_chunk_handlers,
263 _setting_chunk_handlers,
264 _veh_chunk_handlers,
265 _waypoint_chunk_handlers,
266 _depot_chunk_handlers,
267 _order_chunk_handlers,
268 _industry_chunk_handlers,
269 _economy_chunk_handlers,
270 _subsidy_chunk_handlers,
271 _cargomonitor_chunk_handlers,
272 _goal_chunk_handlers,
273 _story_page_chunk_handlers,
274 _league_chunk_handlers,
275 _engine_chunk_handlers,
276 _town_chunk_handlers,
277 _sign_chunk_handlers,
278 _station_chunk_handlers,
279 _company_chunk_handlers,
280 _ai_chunk_handlers,
281 _game_chunk_handlers,
282 _animated_tile_chunk_handlers,
283 _newgrf_chunk_handlers,
284 _group_chunk_handlers,
285 _cargopacket_chunk_handlers,
286 _autoreplace_chunk_handlers,
287 _labelmaps_chunk_handlers,
288 _linkgraph_chunk_handlers,
289 _airport_chunk_handlers,
290 _object_chunk_handlers,
291 _persistent_storage_chunk_handlers,
292 };
293
294 static std::vector<ChunkHandlerRef> _chunk_handlers;
295
296 if (_chunk_handlers.empty()) {
297 for (auto &chunk_handler_table : _chunk_handler_tables) {
298 for (auto &chunk_handler : chunk_handler_table) {
299 _chunk_handlers.push_back(chunk_handler);
300 }
301 }
302 }
303
304 return _chunk_handlers;
305 }
306
308 static void SlNullPointers()
309 {
310 _sl.action = SLA_NULL;
311
312 /* We don't want any savegame conversion code to run
313 * during NULLing; especially those that try to get
314 * pointers from other pools. */
315 _sl_version = SAVEGAME_VERSION;
316
317 for (const ChunkHandler &ch : ChunkHandlers()) {
318 Debug(sl, 3, "Nulling pointers for {:c}{:c}{:c}{:c}", ch.id >> 24, ch.id >> 16, ch.id >> 8, ch.id);
319 ch.FixPointers();
320 }
321
322 assert(_sl.action == SLA_NULL);
323 }
324
333 void NORETURN SlError(StringID string, const char *extra_msg)
334 {
335 /* Distinguish between loading into _load_check_data vs. normal save/load. */
336 if (_sl.action == SLA_LOAD_CHECK) {
337 _load_check_data.error = string;
338 free(_load_check_data.error_data);
339 _load_check_data.error_data = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
340 } else {
341 _sl.error_str = string;
342 free(_sl.extra_msg);
343 _sl.extra_msg = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
344 }
345
346 /* We have to nullptr all pointers here; we might be in a state where
347 * the pointers are actually filled with indices, which means that
348 * when we access them during cleaning the pool dereferences of
349 * those indices will be made with segmentation faults as result. */
350 if (_sl.action == SLA_LOAD || _sl.action == SLA_PTRS) SlNullPointers();
351
352 /* Logging could be active. */
353 GamelogStopAnyAction();
354
355 throw std::exception();
356 }
357
365 void NORETURN SlErrorCorrupt(const char *msg)
366 {
367 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, msg);
368 }
369
377 void NORETURN SlErrorCorruptFmt(const char *format, ...)
378 {
379 va_list ap;
380 char msg[256];
381
382 va_start(ap, format);
383 vseprintf(msg, lastof(msg), format, ap);
384 va_end(ap);
385
386 SlErrorCorrupt(msg);
387 }
388
389
390 typedef void (*AsyncSaveFinishProc)();
391 static std::atomic<AsyncSaveFinishProc> _async_save_finish;
392 static std::thread _save_thread;
393
398 static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
399 {
400 if (_exit_game) return;
401 while (_async_save_finish.load(std::memory_order_acquire) != nullptr) CSleep(10);
402
403 _async_save_finish.store(proc, std::memory_order_release);
404 }
405
409 void ProcessAsyncSaveFinish()
410 {
411 AsyncSaveFinishProc proc = _async_save_finish.exchange(nullptr, std::memory_order_acq_rel);
412 if (proc == nullptr) return;
413
414 proc();
415
416 if (_save_thread.joinable()) {
417 _save_thread.join();
418 }
419 }
420
425 byte SlReadByte()
426 {
427 return _sl.reader->ReadByte();
428 }
429
434 void SlWriteByte(byte b)
435 {
436 _sl.dumper->WriteByte(b);
437 }
438
439 static inline int SlReadUint16()
440 {
441 int x = SlReadByte() << 8;
442 return x | SlReadByte();
443 }
444
445 static inline uint32 SlReadUint32()
446 {
447 uint32 x = SlReadUint16() << 16;
448 return x | SlReadUint16();
449 }
450
451 static inline uint64 SlReadUint64()
452 {
453 uint32 x = SlReadUint32();
454 uint32 y = SlReadUint32();
455 return (uint64)x << 32 | y;
456 }
457
458 static inline void SlWriteUint16(uint16 v)
459 {
460 SlWriteByte(GB(v, 8, 8));
461 SlWriteByte(GB(v, 0, 8));
462 }
463
464 static inline void SlWriteUint32(uint32 v)
465 {
466 SlWriteUint16(GB(v, 16, 16));
467 SlWriteUint16(GB(v, 0, 16));
468 }
469
470 static inline void SlWriteUint64(uint64 x)
471 {
472 SlWriteUint32((uint32)(x >> 32));
473 SlWriteUint32((uint32)x);
474 }
475
485 static uint SlReadSimpleGamma()
486 {
487 uint i = SlReadByte();
488 if (HasBit(i, 7)) {
489 i &= ~0x80;
490 if (HasBit(i, 6)) {
491 i &= ~0x40;
492 if (HasBit(i, 5)) {
493 i &= ~0x20;
494 if (HasBit(i, 4)) {
495 i &= ~0x10;
496 if (HasBit(i, 3)) {
497 SlErrorCorrupt("Unsupported gamma");
498 }
499 i = SlReadByte(); // 32 bits only.
500 }
501 i = (i << 8) | SlReadByte();
502 }
503 i = (i << 8) | SlReadByte();
504 }
505 i = (i << 8) | SlReadByte();
506 }
507 return i;
508 }
509
527 static void SlWriteSimpleGamma(size_t i)
528 {
529 if (i >= (1 << 7)) {
530 if (i >= (1 << 14)) {
531 if (i >= (1 << 21)) {
532 if (i >= (1 << 28)) {
533 assert(i <= UINT32_MAX); // We can only support 32 bits for now.
534 SlWriteByte((byte)(0xF0));
535 SlWriteByte((byte)(i >> 24));
536 } else {
537 SlWriteByte((byte)(0xE0 | (i >> 24)));
538 }
539 SlWriteByte((byte)(i >> 16));
540 } else {
541 SlWriteByte((byte)(0xC0 | (i >> 16)));
542 }
543 SlWriteByte((byte)(i >> 8));
544 } else {
545 SlWriteByte((byte)(0x80 | (i >> 8)));
546 }
547 }
548 SlWriteByte((byte)i);
549 }
550
552 static inline uint SlGetGammaLength(size_t i)
553 {
554 return 1 + (i >= (1 << 7)) + (i >= (1 << 14)) + (i >= (1 << 21)) + (i >= (1 << 28));
555 }
556
557 static inline uint SlReadSparseIndex()
558 {
559 return SlReadSimpleGamma();
560 }
561
562 static inline void SlWriteSparseIndex(uint index)
563 {
564 SlWriteSimpleGamma(index);
565 }
566
567 static inline uint SlReadArrayLength()
568 {
569 return SlReadSimpleGamma();
570 }
571
572 static inline void SlWriteArrayLength(size_t length)
573 {
574 SlWriteSimpleGamma(length);
575 }
576
577 static inline uint SlGetArrayLength(size_t length)
578 {
579 return SlGetGammaLength(length);
580 }
581
585 static uint8 GetSavegameFileType(const SaveLoad &sld)
586 {
587 switch (sld.cmd) {
588 case SL_VAR:
589 return GetVarFileType(sld.conv); break;
590
591 case SL_STR:
592 case SL_STDSTR:
593 case SL_ARR:
594 case SL_VECTOR:
595 case SL_DEQUE:
596 return GetVarFileType(sld.conv) | SLE_FILE_HAS_LENGTH_FIELD; break;
597
598 case SL_REF:
599 return IsSavegameVersionBefore(SLV_69) ? SLE_FILE_U16 : SLE_FILE_U32;
600
601 case SL_REFLIST:
602 return (IsSavegameVersionBefore(SLV_69) ? SLE_FILE_U16 : SLE_FILE_U32) | SLE_FILE_HAS_LENGTH_FIELD;
603
604 case SL_SAVEBYTE:
605 return SLE_FILE_U8;
606
607 case SL_STRUCT:
608 case SL_STRUCTLIST:
609 return SLE_FILE_STRUCT | SLE_FILE_HAS_LENGTH_FIELD;
610
611 default: NOT_REACHED();
612 }
613 }
614
621 static inline uint SlCalcConvMemLen(VarType conv)
622 {
623 static const byte conv_mem_size[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
624
625 switch (GetVarMemType(conv)) {
626 case SLE_VAR_STRB:
627 case SLE_VAR_STR:
628 case SLE_VAR_STRQ:
629 return SlReadArrayLength();
630
631 default:
632 uint8 type = GetVarMemType(conv) >> 4;
633 assert(type < lengthof(conv_mem_size));
634 return conv_mem_size[type];
635 }
636 }
637
644 static inline byte SlCalcConvFileLen(VarType conv)
645 {
646 static const byte conv_file_size[] = {0, 1, 1, 2, 2, 4, 4, 8, 8, 2};
647
648 uint8 type = GetVarFileType(conv);
649 assert(type < lengthof(conv_file_size));
650 return conv_file_size[type];
651 }
652
654 static inline size_t SlCalcRefLen()
655 {
656 return IsSavegameVersionBefore(SLV_69) ? 2 : 4;
657 }
658
659 void SlSetArrayIndex(uint index)
660 {
661 _sl.need_length = NL_WANTLENGTH;
662 _sl.array_index = index;
663 }
664
665 static size_t _next_offs;
666
671 int SlIterateArray()
672 {
673 int index;
674
675 /* After reading in the whole array inside the loop
676 * we must have read in all the data, so we must be at end of current block. */
677 if (_next_offs != 0 && _sl.reader->GetSize() != _next_offs) SlErrorCorrupt("Invalid chunk size");
678
679 for (;;) {
680 uint length = SlReadArrayLength();
681 if (length == 0) {
682 assert(!_sl.expect_table_header);
683 _next_offs = 0;
684 return -1;
685 }
686
687 _sl.obj_len = --length;
688 _next_offs = _sl.reader->GetSize() + length;
689
690 if (_sl.expect_table_header) {
691 _sl.expect_table_header = false;
692 return INT32_MAX;
693 }
694
695 switch (_sl.block_mode) {
696 case CH_SPARSE_TABLE:
697 case CH_SPARSE_ARRAY: index = (int)SlReadSparseIndex(); break;
698 case CH_TABLE:
699 case CH_ARRAY: index = _sl.array_index++; break;
700 default:
701 Debug(sl, 0, "SlIterateArray error");
702 return -1; // error
703 }
704
705 if (length != 0) return index;
706 }
707 }
708
712 void SlSkipArray()
713 {
714 while (SlIterateArray() != -1) {
715 SlSkipBytes(_next_offs - _sl.reader->GetSize());
716 }
717 }
718
724 void SlSetLength(size_t length)
725 {
726 assert(_sl.action == SLA_SAVE);
727
728 switch (_sl.need_length) {
729 case NL_WANTLENGTH:
730 _sl.need_length = NL_NONE;
731 if ((_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE) && _sl.expect_table_header) {
732 _sl.expect_table_header = false;
733 SlWriteArrayLength(length + 1);
734 break;
735 }
736
737 switch (_sl.block_mode) {
738 case CH_RIFF:
739 /* Ugly encoding of >16M RIFF chunks
740 * The lower 24 bits are normal
741 * The uppermost 4 bits are bits 24:27 */
742 assert(length < (1 << 28));
743 SlWriteUint32((uint32)((length & 0xFFFFFF) | ((length >> 24) << 28)));
744 break;
745 case CH_TABLE:
746 case CH_ARRAY:
747 assert(_sl.last_array_index <= _sl.array_index);
748 while (++_sl.last_array_index <= _sl.array_index) {
749 SlWriteArrayLength(1);
750 }
751 SlWriteArrayLength(length + 1);
752 break;
753 case CH_SPARSE_TABLE:
754 case CH_SPARSE_ARRAY:
755 SlWriteArrayLength(length + 1 + SlGetArrayLength(_sl.array_index)); // Also include length of sparse index.
756 SlWriteSparseIndex(_sl.array_index);
757 break;
758 default: NOT_REACHED();
759 }
760 break;
761
762 case NL_CALCLENGTH:
763 _sl.obj_len += (int)length;
764 break;
765
766 default: NOT_REACHED();
767 }
768 }
769
776 static void SlCopyBytes(void *ptr, size_t length)
777 {
778 byte *p = (byte *)ptr;
779
780 switch (_sl.action) {
781 case SLA_LOAD_CHECK:
782 case SLA_LOAD:
783 for (; length != 0; length--) *p++ = SlReadByte();
784 break;
785 case SLA_SAVE:
786 for (; length != 0; length--) SlWriteByte(*p++);
787 break;
788 default: NOT_REACHED();
789 }
790 }
791
793 size_t SlGetFieldLength()
794 {
795 return _sl.obj_len;
796 }
797
805 int64 ReadValue(const void *ptr, VarType conv)
806 {
807 switch (GetVarMemType(conv)) {
808 case SLE_VAR_BL: return (*(const bool *)ptr != 0);
809 case SLE_VAR_I8: return *(const int8 *)ptr;
810 case SLE_VAR_U8: return *(const byte *)ptr;
811 case SLE_VAR_I16: return *(const int16 *)ptr;
812 case SLE_VAR_U16: return *(const uint16*)ptr;
813 case SLE_VAR_I32: return *(const int32 *)ptr;
814 case SLE_VAR_U32: return *(const uint32*)ptr;
815 case SLE_VAR_I64: return *(const int64 *)ptr;
816 case SLE_VAR_U64: return *(const uint64*)ptr;
817 case SLE_VAR_NULL:return 0;
818 default: NOT_REACHED();
819 }
820 }
821
829 void WriteValue(void *ptr, VarType conv, int64 val)
830 {
831 switch (GetVarMemType(conv)) {
832 case SLE_VAR_BL: *(bool *)ptr = (val != 0); break;
833 case SLE_VAR_I8: *(int8 *)ptr = val; break;
834 case SLE_VAR_U8: *(byte *)ptr = val; break;
835 case SLE_VAR_I16: *(int16 *)ptr = val; break;
836 case SLE_VAR_U16: *(uint16*)ptr = val; break;
837 case SLE_VAR_I32: *(int32 *)ptr = val; break;
838 case SLE_VAR_U32: *(uint32*)ptr = val; break;
839 case SLE_VAR_I64: *(int64 *)ptr = val; break;
840 case SLE_VAR_U64: *(uint64*)ptr = val; break;
841 case SLE_VAR_NAME: *reinterpret_cast<std::string *>(ptr) = CopyFromOldName(val); break;
842 case SLE_VAR_NULL: break;
843 default: NOT_REACHED();
844 }
845 }
846
855 static void SlSaveLoadConv(void *ptr, VarType conv)
856 {
857 switch (_sl.action) {
858 case SLA_SAVE: {
859 int64 x = ReadValue(ptr, conv);
860
861 /* Write the value to the file and check if its value is in the desired range */
862 switch (GetVarFileType(conv)) {
863 case SLE_FILE_I8: assert(x >= -128 && x <= 127); SlWriteByte(x);break;
864 case SLE_FILE_U8: assert(x >= 0 && x <= 255); SlWriteByte(x);break;
865 case SLE_FILE_I16:assert(x >= -32768 && x <= 32767); SlWriteUint16(x);break;
866 case SLE_FILE_STRINGID:
867 case SLE_FILE_U16:assert(x >= 0 && x <= 65535); SlWriteUint16(x);break;
868 case SLE_FILE_I32:
869 case SLE_FILE_U32: SlWriteUint32((uint32)x);break;
870 case SLE_FILE_I64:
871 case SLE_FILE_U64: SlWriteUint64(x);break;
872 default: NOT_REACHED();
873 }
874 break;
875 }
876 case SLA_LOAD_CHECK:
877 case SLA_LOAD: {
878 int64 x;
879 /* Read a value from the file */
880 switch (GetVarFileType(conv)) {
881 case SLE_FILE_I8: x = (int8 )SlReadByte(); break;
882 case SLE_FILE_U8: x = (byte )SlReadByte(); break;
883 case SLE_FILE_I16: x = (int16 )SlReadUint16(); break;
884 case SLE_FILE_U16: x = (uint16)SlReadUint16(); break;
885 case SLE_FILE_I32: x = (int32 )SlReadUint32(); break;
886 case SLE_FILE_U32: x = (uint32)SlReadUint32(); break;
887 case SLE_FILE_I64: x = (int64 )SlReadUint64(); break;
888 case SLE_FILE_U64: x = (uint64)SlReadUint64(); break;
889 case SLE_FILE_STRINGID: x = RemapOldStringID((uint16)SlReadUint16()); break;
890 default: NOT_REACHED();
891 }
892
893 /* Write The value to the struct. These ARE endian safe. */
894 WriteValue(ptr, conv, x);
895 break;
896 }
897 case SLA_PTRS: break;
898 case SLA_NULL: break;
899 default: NOT_REACHED();
900 }
901 }
902
912 static inline size_t SlCalcNetStringLen(const char *ptr, size_t length)
913 {
914 if (ptr == nullptr) return 0;
915 return std::min(strlen(ptr), length - 1);
916 }
917
927 static inline size_t SlCalcStringLen(const void *ptr, size_t length, VarType conv)
928 {
929 size_t len;
930 const char *str;
931
932 switch (GetVarMemType(conv)) {
933 default: NOT_REACHED();
934 case SLE_VAR_STR:
935 case SLE_VAR_STRQ:
936 str = *(const char * const *)ptr;
937 len = SIZE_MAX;
938 break;
939 case SLE_VAR_STRB:
940 str = (const char *)ptr;
941 len = length;
942 break;
943 }
944
945 len = SlCalcNetStringLen(str, len);
946 return len + SlGetArrayLength(len); // also include the length of the index
947 }
948
956 static inline size_t SlCalcStdStringLen(const void *ptr)
957 {
958 const std::string *str = reinterpret_cast<const std::string *>(ptr);
959
960 size_t len = str->length();
961 return len + SlGetArrayLength(len); // also include the length of the index
962 }
963
970 static void SlString(void *ptr, size_t length, VarType conv)
971 {
972 switch (_sl.action) {
973 case SLA_SAVE: {
974 size_t len;
975 switch (GetVarMemType(conv)) {
976 default: NOT_REACHED();
977 case SLE_VAR_STRB:
978 len = SlCalcNetStringLen((char *)ptr, length);
979 break;
980 case SLE_VAR_STR:
981 case SLE_VAR_STRQ:
982 ptr = *(char **)ptr;
983 len = SlCalcNetStringLen((char *)ptr, SIZE_MAX);
984 break;
985 }
986
987 SlWriteArrayLength(len);
988 SlCopyBytes(ptr, len);
989 break;
990 }
991 case SLA_LOAD_CHECK:
992 case SLA_LOAD: {
993 size_t len = SlReadArrayLength();
994
995 switch (GetVarMemType(conv)) {
996 default: NOT_REACHED();
997 case SLE_VAR_NULL:
998 SlSkipBytes(len);
999 return;
1000 case SLE_VAR_STRB:
1001 if (len >= length) {
1002 Debug(sl, 1, "String length in savegame is bigger than buffer, truncating");
1003 SlCopyBytes(ptr, length);
1004 SlSkipBytes(len - length);
1005 len = length - 1;
1006 } else {
1007 SlCopyBytes(ptr, len);
1008 }
1009 break;
1010 case SLE_VAR_STR:
1011 case SLE_VAR_STRQ: // Malloc'd string, free previous incarnation, and allocate
1012 free(*(char **)ptr);
1013 if (len == 0) {
1014 *(char **)ptr = nullptr;
1015 return;
1016 } else {
1017 *(char **)ptr = MallocT<char>(len + 1); // terminating '\0'
1018 ptr = *(char **)ptr;
1019 SlCopyBytes(ptr, len);
1020 }
1021 break;
1022 }
1023
1024 ((char *)ptr)[len] = '\0'; // properly terminate the string
1025 StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK;
1026 if ((conv & SLF_ALLOW_CONTROL) != 0) {
1027 settings = settings | SVS_ALLOW_CONTROL_CODE;
1028 if (IsSavegameVersionBefore(SLV_169)) {
1029 str_fix_scc_encoded((char *)ptr, (char *)ptr + len);
1030 }
1031 }
1032 if ((conv & SLF_ALLOW_NEWLINE) != 0) {
1033 settings = settings | SVS_ALLOW_NEWLINE;
1034 }
1035 StrMakeValidInPlace((char *)ptr, (char *)ptr + len, settings);
1036 break;
1037 }
1038 case SLA_PTRS: break;
1039 case SLA_NULL: break;
1040 default: NOT_REACHED();
1041 }
1042 }
1043
1049 static void SlStdString(void *ptr, VarType conv)
1050 {
1051 std::string *str = reinterpret_cast<std::string *>(ptr);
1052
1053 switch (_sl.action) {
1054 case SLA_SAVE: {
1055 size_t len = str->length();
1056 SlWriteArrayLength(len);
1057 SlCopyBytes(const_cast<void *>(static_cast<const void *>(str->c_str())), len);
1058 break;
1059 }
1060
1061 case SLA_LOAD_CHECK:
1062 case SLA_LOAD: {
1063 size_t len = SlReadArrayLength();
1064 if (GetVarMemType(conv) == SLE_VAR_NULL) {
1065 SlSkipBytes(len);
1066 return;
1067 }
1068
1069 char *buf = AllocaM(char, len + 1);
1070 SlCopyBytes(buf, len);
1071 buf[len] = '\0'; // properly terminate the string
1072
1073 StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK;
1074 if ((conv & SLF_ALLOW_CONTROL) != 0) {
1075 settings = settings | SVS_ALLOW_CONTROL_CODE;
1076 if (IsSavegameVersionBefore(SLV_169)) {
1077 str_fix_scc_encoded(buf, buf + len);
1078 }
1079 }
1080 if ((conv & SLF_ALLOW_NEWLINE) != 0) {
1081 settings = settings | SVS_ALLOW_NEWLINE;
1082 }
1083 StrMakeValidInPlace(buf, buf + len, settings);
1084
1085 // Store sanitized string.
1086 str->assign(buf);
1087 }
1088
1089 case SLA_PTRS: break;
1090 case SLA_NULL: break;
1091 default: NOT_REACHED();
1092 }
1093 }
1094
1103 static void SlCopyInternal(void *object, size_t length, VarType conv)
1104 {
1105 if (GetVarMemType(conv) == SLE_VAR_NULL) {
1106 assert(_sl.action != SLA_SAVE); // Use SL_NULL if you want to write null-bytes
1107 SlSkipBytes(length * SlCalcConvFileLen(conv));
1108 return;
1109 }
1110
1111 /* NOTICE - handle some buggy stuff, in really old versions everything was saved
1112 * as a byte-type. So detect this, and adjust object size accordingly */
1113 if (_sl.action != SLA_SAVE && _sl_version == 0) {
1114 /* all objects except difficulty settings */
1115 if (conv == SLE_INT16 || conv == SLE_UINT16 || conv == SLE_STRINGID ||
1116 conv == SLE_INT32 || conv == SLE_UINT32) {
1117 SlCopyBytes(object, length * SlCalcConvFileLen(conv));
1118 return;
1119 }
1120 /* used for conversion of Money 32bit->64bit */
1121 if (conv == (SLE_FILE_I32 | SLE_VAR_I64)) {
1122 for (uint i = 0; i < length; i++) {
1123 ((int64*)object)[i] = (int32)BSWAP32(SlReadUint32());
1124 }
1125 return;
1126 }
1127 }
1128
1129 /* If the size of elements is 1 byte both in file and memory, no special
1130 * conversion is needed, use specialized copy-copy function to speed up things */
1131 if (conv == SLE_INT8 || conv == SLE_UINT8) {
1132 SlCopyBytes(object, length);
1133 } else {
1134 byte *a = (byte*)object;
1135 byte mem_size = SlCalcConvMemLen(conv);
1136
1137 for (; length != 0; length --) {
1138 SlSaveLoadConv(a, conv);
1139 a += mem_size; // get size
1140 }
1141 }
1142 }
1143
1152 void SlCopy(void *object, size_t length, VarType conv)
1153 {
1154 if (_sl.action == SLA_PTRS || _sl.action == SLA_NULL) return;
1155
1156 /* Automatically calculate the length? */
1157 if (_sl.need_length != NL_NONE) {
1158 SlSetLength(length * SlCalcConvFileLen(conv));
1159 /* Determine length only? */
1160 if (_sl.need_length == NL_CALCLENGTH) return;
1161 }
1162
1163 SlCopyInternal(object, length, conv);
1164 }
1165
1171 static inline size_t SlCalcArrayLen(size_t length, VarType conv)
1172 {
1173 return SlCalcConvFileLen(conv) * length + SlGetArrayLength(length);
1174 }
1175
1182 static void SlArray(void *array, size_t length, VarType conv)
1183 {
1184 switch (_sl.action) {
1185 case SLA_SAVE:
1186 SlWriteArrayLength(length);
1187 SlCopyInternal(array, length, conv);
1188 return;
1189
1190 case SLA_LOAD_CHECK:
1191 case SLA_LOAD: {
1192 if (!IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH)) {
1193 size_t sv_length = SlReadArrayLength();
1194 if (GetVarMemType(conv) == SLE_VAR_NULL) {
1195 /* We don't know this field, so we assume the length in the savegame is correct. */
1196 length = sv_length;
1197 } else if (sv_length != length) {
1198 /* If the SLE_ARR changes size, a savegame bump is required
1199 * and the developer should have written conversion lines.
1200 * Error out to make this more visible. */
1201 SlErrorCorrupt("Fixed-length array is of wrong length");
1202 }
1203 }
1204
1205 SlCopyInternal(array, length, conv);
1206 return;
1207 }
1208
1209 case SLA_PTRS:
1210 case SLA_NULL:
1211 return;
1212
1213 default:
1214 NOT_REACHED();
1215 }
1216 }
1217
1228 static size_t ReferenceToInt(const void *obj, SLRefType rt)
1229 {
1230 assert(_sl.action == SLA_SAVE);
1231
1232 if (obj == nullptr) return 0;
1233
1234 switch (rt) {
1235 case REF_VEHICLE_OLD: // Old vehicles we save as new ones
1236 case REF_VEHICLE: return ((const Vehicle*)obj)->index + 1;
1237 case REF_STATION: return ((const Station*)obj)->index + 1;
1238 case REF_TOWN: return ((const Town*)obj)->index + 1;
1239 case REF_ORDER: return ((const Order*)obj)->index + 1;
1240 case REF_ROADSTOPS: return ((const RoadStop*)obj)->index + 1;
1241 case REF_ENGINE_RENEWS: return ((const EngineRenew*)obj)->index + 1;
1242 case REF_CARGO_PACKET: return ((const CargoPacket*)obj)->index + 1;
1243 case REF_ORDERLIST: return ((const OrderList*)obj)->index + 1;
1244 case REF_STORAGE: return ((const PersistentStorage*)obj)->index + 1;
1245 case REF_LINK_GRAPH: return ((const LinkGraph*)obj)->index + 1;
1246 case REF_LINK_GRAPH_JOB: return ((const LinkGraphJob*)obj)->index + 1;
1247 default: NOT_REACHED();
1248 }
1249 }
1250
1261 static void *IntToReference(size_t index, SLRefType rt)
1262 {
1263 static_assert(sizeof(size_t) <= sizeof(void *));
1264
1265 assert(_sl.action == SLA_PTRS);
1266
1267 /* After version 4.3 REF_VEHICLE_OLD is saved as REF_VEHICLE,
1268 * and should be loaded like that */
1269 if (rt == REF_VEHICLE_OLD && !IsSavegameVersionBefore(SLV_4, 4)) {
1270 rt = REF_VEHICLE;
1271 }
1272
1273 /* No need to look up nullptr pointers, just return immediately */
1274 if (index == (rt == REF_VEHICLE_OLD ? 0xFFFF : 0)) return nullptr;
1275
1276 /* Correct index. Old vehicles were saved differently:
1277 * invalid vehicle was 0xFFFF, now we use 0x0000 for everything invalid. */
1278 if (rt != REF_VEHICLE_OLD) index--;
1279
1280 switch (rt) {
1281 case REF_ORDERLIST:
1282 if (OrderList::IsValidID(index)) return OrderList::Get(index);
1283 SlErrorCorrupt("Referencing invalid OrderList");
1284
1285 case REF_ORDER:
1286 if (Order::IsValidID(index)) return Order::Get(index);
1287 /* in old versions, invalid order was used to mark end of order list */
1288 if (IsSavegameVersionBefore(SLV_5, 2)) return nullptr;
1289 SlErrorCorrupt("Referencing invalid Order");
1290
1291 case REF_VEHICLE_OLD:
1292 case REF_VEHICLE:
1293 if (Vehicle::IsValidID(index)) return Vehicle::Get(index);
1294 SlErrorCorrupt("Referencing invalid Vehicle");
1295
1296 case REF_STATION:
1297 if (Station::IsValidID(index)) return Station::Get(index);
1298 SlErrorCorrupt("Referencing invalid Station");
1299
1300 case REF_TOWN:
1301 if (Town::IsValidID(index)) return Town::Get(index);
1302 SlErrorCorrupt("Referencing invalid Town");
1303
1304 case REF_ROADSTOPS:
1305 if (RoadStop::IsValidID(index)) return RoadStop::Get(index);
1306 SlErrorCorrupt("Referencing invalid RoadStop");
1307
1308 case REF_ENGINE_RENEWS:
1309 if (EngineRenew::IsValidID(index)) return EngineRenew::Get(index);
1310 SlErrorCorrupt("Referencing invalid EngineRenew");
1311
1312 case REF_CARGO_PACKET:
1313 if (CargoPacket::IsValidID(index)) return CargoPacket::Get(index);
1314 SlErrorCorrupt("Referencing invalid CargoPacket");
1315
1316 case REF_STORAGE:
1317 if (PersistentStorage::IsValidID(index)) return PersistentStorage::Get(index);
1318 SlErrorCorrupt("Referencing invalid PersistentStorage");
1319
1320 case REF_LINK_GRAPH:
1321 if (LinkGraph::IsValidID(index)) return LinkGraph::Get(index);
1322 SlErrorCorrupt("Referencing invalid LinkGraph");
1323
1324 case REF_LINK_GRAPH_JOB:
1325 if (LinkGraphJob::IsValidID(index)) return LinkGraphJob::Get(index);
1326 SlErrorCorrupt("Referencing invalid LinkGraphJob");
1327
1328 default: NOT_REACHED();
1329 }
1330 }
1331
1337 void SlSaveLoadRef(void *ptr, VarType conv)
1338 {
1339 switch (_sl.action) {
1340 case SLA_SAVE:
1341 SlWriteUint32((uint32)ReferenceToInt(*(void **)ptr, (SLRefType)conv));
1342 break;
1343 case SLA_LOAD_CHECK:
1344 case SLA_LOAD:
1345 *(size_t *)ptr = IsSavegameVersionBefore(SLV_69) ? SlReadUint16() : SlReadUint32();
1346 break;
1347 case SLA_PTRS:
1348 *(void **)ptr = IntToReference(*(size_t *)ptr, (SLRefType)conv);
1349 break;
1350 case SLA_NULL:
1351 *(void **)ptr = nullptr;
1352 break;
1353 default: NOT_REACHED();
1354 }
1355 }
1356
1360 template <template<typename, typename> typename Tstorage, typename Tvar, typename Tallocator = std::allocator<Tvar>>
1361 class SlStorageHelper {
1362 typedef Tstorage<Tvar, Tallocator> SlStorageT;
1363 public:
1370 static size_t SlCalcLen(const void *storage, VarType conv, SaveLoadType cmd = SL_VAR)
1371 {
1372 assert(cmd == SL_VAR || cmd == SL_REF);
1373
1374 const SlStorageT *list = static_cast<const SlStorageT *>(storage);
1375
1376 int type_size = SlGetArrayLength(list->size());
1377 int item_size = SlCalcConvFileLen(cmd == SL_VAR ? conv : (VarType)SLE_FILE_U32);
1378 return list->size() * item_size + type_size;
1379 }
1380
1381 static void SlSaveLoadMember(SaveLoadType cmd, Tvar *item, VarType conv)
1382 {
1383 switch (cmd) {
1384 case SL_VAR: SlSaveLoadConv(item, conv); break;
1385 case SL_REF: SlSaveLoadRef(item, conv); break;
1386 default:
1387 NOT_REACHED();
1388 }
1389 }
1390
1397 static void SlSaveLoad(void *storage, VarType conv, SaveLoadType cmd = SL_VAR)
1398 {
1399 assert(cmd == SL_VAR || cmd == SL_REF);
1400
1401 SlStorageT *list = static_cast<SlStorageT *>(storage);
1402
1403 switch (_sl.action) {
1404 case SLA_SAVE:
1405 SlWriteArrayLength(list->size());
1406
1407 for (auto &item : *list) {
1408 SlSaveLoadMember(cmd, &item, conv);
1409 }
1410 break;
1411
1412 case SLA_LOAD_CHECK:
1413 case SLA_LOAD: {
1414 size_t length;
1415 switch (cmd) {
1416 case SL_VAR: length = IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? SlReadUint32() : SlReadArrayLength(); break;
1417 case SL_REF: length = IsSavegameVersionBefore(SLV_69) ? SlReadUint16() : IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH) ? SlReadUint32() : SlReadArrayLength(); break;
1418 default: NOT_REACHED();
1419 }
1420
1421 /* Load each value and push to the end of the storage. */
1422 for (size_t i = 0; i < length; i++) {
1423 Tvar &data = list->emplace_back();
1424 SlSaveLoadMember(cmd, &data, conv);
1425 }
1426 break;
1427 }
1428
1429 case SLA_PTRS:
1430 for (auto &item : *list) {
1431 SlSaveLoadMember(cmd, &item, conv);
1432 }
1433 break;
1434
1435 case SLA_NULL:
1436 list->clear();
1437 break;
1438
1439 default: NOT_REACHED();
1440 }
1441 }
1442 };
1443
1449 static inline size_t SlCalcRefListLen(const void *list, VarType conv)
1450 {
1451 return SlStorageHelper<std::list, void *>::SlCalcLen(list, conv, SL_REF);
1452 }
1453
1459 static void SlRefList(void *list, VarType conv)
1460 {
1461 /* Automatically calculate the length? */
1462 if (_sl.need_length != NL_NONE) {
1463 SlSetLength(SlCalcRefListLen(list, conv));
1464 /* Determine length only? */
1465 if (_sl.need_length == NL_CALCLENGTH) return;
1466 }
1467
1468 SlStorageHelper<std::list, void *>::SlSaveLoad(list, conv, SL_REF);
1469 }
1470
1476 static inline size_t SlCalcDequeLen(const void *deque, VarType conv)
1477 {
1478 switch (GetVarMemType(conv)) {
1479 case SLE_VAR_BL: return SlStorageHelper<std::deque, bool>::SlCalcLen(deque, conv);
1480 case SLE_VAR_I8: return SlStorageHelper<std::deque, int8>::SlCalcLen(deque, conv);
1481 case SLE_VAR_U8: return SlStorageHelper<std::deque, uint8>::SlCalcLen(deque, conv);
1482 case SLE_VAR_I16: return SlStorageHelper<std::deque, int16>::SlCalcLen(deque, conv);
1483 case SLE_VAR_U16: return SlStorageHelper<std::deque, uint16>::SlCalcLen(deque, conv);
1484 case SLE_VAR_I32: return SlStorageHelper<std::deque, int32>::SlCalcLen(deque, conv);
1485 case SLE_VAR_U32: return SlStorageHelper<std::deque, uint32>::SlCalcLen(deque, conv);
1486 case SLE_VAR_I64: return SlStorageHelper<std::deque, int64>::SlCalcLen(deque, conv);
1487 case SLE_VAR_U64: return SlStorageHelper<std::deque, uint64>::SlCalcLen(deque, conv);
1488 default: NOT_REACHED();
1489 }
1490 }
1491
1497 static void SlDeque(void *deque, VarType conv)
1498 {
1499 switch (GetVarMemType(conv)) {
1500 case SLE_VAR_BL: SlStorageHelper<std::deque, bool>::SlSaveLoad(deque, conv); break;
1501 case SLE_VAR_I8: SlStorageHelper<std::deque, int8>::SlSaveLoad(deque, conv); break;
1502 case SLE_VAR_U8: SlStorageHelper<std::deque, uint8>::SlSaveLoad(deque, conv); break;
1503 case SLE_VAR_I16: SlStorageHelper<std::deque, int16>::SlSaveLoad(deque, conv); break;
1504 case SLE_VAR_U16: SlStorageHelper<std::deque, uint16>::SlSaveLoad(deque, conv); break;
1505 case SLE_VAR_I32: SlStorageHelper<std::deque, int32>::SlSaveLoad(deque, conv); break;
1506 case SLE_VAR_U32: SlStorageHelper<std::deque, uint32>::SlSaveLoad(deque, conv); break;
1507 case SLE_VAR_I64: SlStorageHelper<std::deque, int64>::SlSaveLoad(deque, conv); break;
1508 case SLE_VAR_U64: SlStorageHelper<std::deque, uint64>::SlSaveLoad(deque, conv); break;
1509 default: NOT_REACHED();
1510 }
1511 }
1512
1518 static inline size_t SlCalcVectorLen(const void *vector, VarType conv)
1519 {
1520 switch (GetVarMemType(conv)) {
1521 case SLE_VAR_BL: NOT_REACHED(); // Not supported
1522 case SLE_VAR_I8: return SlStorageHelper<std::vector, int8>::SlCalcLen(vector, conv);
1523 case SLE_VAR_U8: return SlStorageHelper<std::vector, uint8>::SlCalcLen(vector, conv);
1524 case SLE_VAR_I16: return SlStorageHelper<std::vector, int16>::SlCalcLen(vector, conv);
1525 case SLE_VAR_U16: return SlStorageHelper<std::vector, uint16>::SlCalcLen(vector, conv);
1526 case SLE_VAR_I32: return SlStorageHelper<std::vector, int32>::SlCalcLen(vector, conv);
1527 case SLE_VAR_U32: return SlStorageHelper<std::vector, uint32>::SlCalcLen(vector, conv);
1528 case SLE_VAR_I64: return SlStorageHelper<std::vector, int64>::SlCalcLen(vector, conv);
1529 case SLE_VAR_U64: return SlStorageHelper<std::vector, uint64>::SlCalcLen(vector, conv);
1530 default: NOT_REACHED();
1531 }
1532 }
1533
1539 static void SlVector(void *vector, VarType conv)
1540 {
1541 switch (GetVarMemType(conv)) {
1542 case SLE_VAR_BL: NOT_REACHED(); // Not supported
1543 case SLE_VAR_I8: SlStorageHelper<std::vector, int8>::SlSaveLoad(vector, conv); break;
1544 case SLE_VAR_U8: SlStorageHelper<std::vector, uint8>::SlSaveLoad(vector, conv); break;
1545 case SLE_VAR_I16: SlStorageHelper<std::vector, int16>::SlSaveLoad(vector, conv); break;
1546 case SLE_VAR_U16: SlStorageHelper<std::vector, uint16>::SlSaveLoad(vector, conv); break;
1547 case SLE_VAR_I32: SlStorageHelper<std::vector, int32>::SlSaveLoad(vector, conv); break;
1548 case SLE_VAR_U32: SlStorageHelper<std::vector, uint32>::SlSaveLoad(vector, conv); break;
1549 case SLE_VAR_I64: SlStorageHelper<std::vector, int64>::SlSaveLoad(vector, conv); break;
1550 case SLE_VAR_U64: SlStorageHelper<std::vector, uint64>::SlSaveLoad(vector, conv); break;
1551 default: NOT_REACHED();
1552 }
1553 }
1554
1556 static inline bool SlIsObjectValidInSavegame(const SaveLoad &sld)
1557 {
1558 return (_sl_version >= sld.version_from && _sl_version < sld.version_to);
1559 }
1560
1566 static size_t SlCalcTableHeader(const SaveLoadTable &slt)
1567 {
1568 size_t length = 0;
1569
1570 for (auto &sld : slt) {
1571 if (!SlIsObjectValidInSavegame(sld)) continue;
1572
1573 length += SlCalcConvFileLen(SLE_UINT8);
1574 length += SlCalcStdStringLen(&sld.name);
1575 }
1576
1577 length += SlCalcConvFileLen(SLE_UINT8); // End-of-list entry.
1578
1579 for (auto &sld : slt) {
1580 if (!SlIsObjectValidInSavegame(sld)) continue;
1581 if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1582 length += SlCalcTableHeader(sld.handler->GetDescription());
1583 }
1584 }
1585
1586 return length;
1587 }
1588
1595 size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt)
1596 {
1597 size_t length = 0;
1598
1599 /* Need to determine the length and write a length tag. */
1600 for (auto &sld : slt) {
1601 length += SlCalcObjMemberLength(object, sld);
1602 }
1603 return length;
1604 }
1605
1606 size_t SlCalcObjMemberLength(const void *object, const SaveLoad &sld)
1607 {
1608 assert(_sl.action == SLA_SAVE);
1609
1610 if (!SlIsObjectValidInSavegame(sld)) return 0;
1611
1612 switch (sld.cmd) {
1613 case SL_VAR: return SlCalcConvFileLen(sld.conv);
1614 case SL_REF: return SlCalcRefLen();
1615 case SL_ARR: return SlCalcArrayLen(sld.length, sld.conv);
1616 case SL_STR: return SlCalcStringLen(GetVariableAddress(object, sld), sld.length, sld.conv);
1617 case SL_REFLIST: return SlCalcRefListLen(GetVariableAddress(object, sld), sld.conv);
1618 case SL_DEQUE: return SlCalcDequeLen(GetVariableAddress(object, sld), sld.conv);
1619 case SL_VECTOR: return SlCalcVectorLen(GetVariableAddress(object, sld), sld.conv);
1620 case SL_STDSTR: return SlCalcStdStringLen(GetVariableAddress(object, sld));
1621 case SL_SAVEBYTE: return 1; // a byte is logically of size 1
1622 case SL_NULL: return SlCalcConvFileLen(sld.conv) * sld.length;
1623
1624 case SL_STRUCT:
1625 case SL_STRUCTLIST: {
1626 NeedLength old_need_length = _sl.need_length;
1627 size_t old_obj_len = _sl.obj_len;
1628
1629 _sl.need_length = NL_CALCLENGTH;
1630 _sl.obj_len = 0;
1631
1632 /* Pretend that we are saving to collect the object size. Other
1633 * means are difficult, as we don't know the length of the list we
1634 * are about to store. */
1635 sld.handler->Save(const_cast<void *>(object));
1636 size_t length = _sl.obj_len;
1637
1638 _sl.obj_len = old_obj_len;
1639 _sl.need_length = old_need_length;
1640
1641 if (sld.cmd == SL_STRUCT) {
1642 length += SlGetArrayLength(1);
1643 }
1644
1645 return length;
1646 }
1647
1648 default: NOT_REACHED();
1649 }
1650 return 0;
1651 }
1652
1658 [[maybe_unused]] static bool IsVariableSizeRight(const SaveLoad &sld)
1659 {
1660 if (GetVarMemType(sld.conv) == SLE_VAR_NULL) return true;
1661
1662 switch (sld.cmd) {
1663 case SL_VAR:
1664 switch (GetVarMemType(sld.conv)) {
1665 case SLE_VAR_BL:
1666 return sld.size == sizeof(bool);
1667 case SLE_VAR_I8:
1668 case SLE_VAR_U8:
1669 return sld.size == sizeof(int8);
1670 case SLE_VAR_I16:
1671 case SLE_VAR_U16:
1672 return sld.size == sizeof(int16);
1673 case SLE_VAR_I32:
1674 case SLE_VAR_U32:
1675 return sld.size == sizeof(int32);
1676 case SLE_VAR_I64:
1677 case SLE_VAR_U64:
1678 return sld.size == sizeof(int64);
1679 case SLE_VAR_NAME:
1680 return sld.size == sizeof(std::string);
1681 default:
1682 return sld.size == sizeof(void *);
1683 }
1684 case SL_REF:
1685 /* These should all be pointer sized. */
1686 return sld.size == sizeof(void *);
1687
1688 case SL_STR:
1689 /* These should be pointer sized, or fixed array. */
1690 return sld.size == sizeof(void *) || sld.size == sld.length;
1691
1692 case SL_STDSTR:
1693 /* These should be all pointers to std::string. */
1694 return sld.size == sizeof(std::string);
1695
1696 default:
1697 return true;
1698 }
1699 }
1700
1701 static bool SlObjectMember(void *object, const SaveLoad &sld)
1702 {
1703 assert(IsVariableSizeRight(sld));
1704
1705 if (!SlIsObjectValidInSavegame(sld)) return false;
1706
1707 VarType conv = GB(sld.conv, 0, 8);
1708 switch (sld.cmd) {
1709 case SL_VAR:
1710 case SL_REF:
1711 case SL_ARR:
1712 case SL_STR:
1713 case SL_REFLIST:
1714 case SL_DEQUE:
1715 case SL_VECTOR:
1716 case SL_STDSTR: {
1717 void *ptr = GetVariableAddress(object, sld);
1718
1719 switch (sld.cmd) {
1720 case SL_VAR: SlSaveLoadConv(ptr, conv); break;
1721 case SL_REF: SlSaveLoadRef(ptr, conv); break;
1722 case SL_ARR: SlArray(ptr, sld.length, conv); break;
1723 case SL_STR: SlString(ptr, sld.length, sld.conv); break;
1724 case SL_REFLIST: SlRefList(ptr, conv); break;
1725 case SL_DEQUE: SlDeque(ptr, conv); break;
1726 case SL_VECTOR: SlVector(ptr, conv); break;
1727 case SL_STDSTR: SlStdString(ptr, sld.conv); break;
1728 default: NOT_REACHED();
1729 }
1730 break;
1731 }
1732
1733 /* SL_SAVEBYTE writes a value to the savegame to identify the type of an object.
1734 * When loading, the value is read explicitly with SlReadByte() to determine which
1735 * object description to use. */
1736 case SL_SAVEBYTE: {
1737 void *ptr = GetVariableAddress(object, sld);
1738
1739 switch (_sl.action) {
1740 case SLA_SAVE: SlWriteByte(*(uint8 *)ptr); break;
1741 case SLA_LOAD_CHECK:
1742 case SLA_LOAD:
1743 case SLA_PTRS:
1744 case SLA_NULL: break;
1745 default: NOT_REACHED();
1746 }
1747 break;
1748 }
1749
1750 case SL_NULL: {
1751 assert(GetVarMemType(sld.conv) == SLE_VAR_NULL);
1752
1753 switch (_sl.action) {
1754 case SLA_LOAD_CHECK:
1755 case SLA_LOAD: SlSkipBytes(SlCalcConvFileLen(sld.conv) * sld.length); break;
1756 case SLA_SAVE: for (int i = 0; i < SlCalcConvFileLen(sld.conv) * sld.length; i++) SlWriteByte(0); break;
1757 case SLA_PTRS:
1758 case SLA_NULL: break;
1759 default: NOT_REACHED();
1760 }
1761 break;
1762 }
1763
1764 case SL_STRUCT:
1765 case SL_STRUCTLIST:
1766 switch (_sl.action) {
1767 case SLA_SAVE: {
1768 if (sld.cmd == SL_STRUCT) {
1769 /* Store in the savegame if this struct was written or not. */
1770 SlSetStructListLength(SlCalcObjMemberLength(object, sld) > SlGetArrayLength(1) ? 1 : 0);
1771 }
1772 sld.handler->Save(object);
1773 break;
1774 }
1775
1776 case SLA_LOAD_CHECK: {
1777 if (sld.cmd == SL_STRUCT && !IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH)) {
1778 SlGetStructListLength(1);
1779 }
1780 sld.handler->LoadCheck(object);
1781 break;
1782 }
1783
1784 case SLA_LOAD: {
1785 if (sld.cmd == SL_STRUCT && !IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH)) {
1786 SlGetStructListLength(1);
1787 }
1788 sld.handler->Load(object);
1789 break;
1790 }
1791
1792 case SLA_PTRS:
1793 sld.handler->FixPointers(object);
1794 break;
1795
1796 case SLA_NULL: break;
1797 default: NOT_REACHED();
1798 }
1799 break;
1800
1801 default: NOT_REACHED();
1802 }
1803 return true;
1804 }
1805
1810 void SlSetStructListLength(size_t length)
1811 {
1812 /* Automatically calculate the length? */
1813 if (_sl.need_length != NL_NONE) {
1814 SlSetLength(SlGetArrayLength(length));
1815 if (_sl.need_length == NL_CALCLENGTH) return;
1816 }
1817
1818 SlWriteArrayLength(length);
1819 }
1820
1826 size_t SlGetStructListLength(size_t limit)
1827 {
1828 size_t length = SlReadArrayLength();
1829 if (length > limit) SlErrorCorrupt("List exceeds storage size");
1830
1831 return length;
1832 }
1833
1839 void SlObject(void *object, const SaveLoadTable &slt)
1840 {
1841 /* Automatically calculate the length? */
1842 if (_sl.need_length != NL_NONE) {
1843 SlSetLength(SlCalcObjLength(object, slt));
1844 if (_sl.need_length == NL_CALCLENGTH) return;
1845 }
1846
1847 for (auto &sld : slt) {
1848 SlObjectMember(object, sld);
1849 }
1850 }
1851
1856 class SlSkipHandler : public SaveLoadHandler {
1857 void Save(void *object) const override
1858 {
1859 NOT_REACHED();
1860 }
1861
1862 void Load(void *object) const override
1863 {
1864 size_t length = SlGetStructListLength(UINT32_MAX);
1865 for (; length > 0; length--) {
1866 SlObject(object, this->GetLoadDescription());
1867 }
1868 }
1869
1870 void LoadCheck(void *object) const override
1871 {
1872 this->Load(object);
1873 }
1874
1875 virtual SaveLoadTable GetDescription() const override
1876 {
1877 return {};
1878 }
1879
1880 virtual SaveLoadCompatTable GetCompatDescription() const override
1881 {
1882 NOT_REACHED();
1883 }
1884 };
1885
1892 std::vector<SaveLoad> SlTableHeader(const SaveLoadTable &slt)
1893 {
1894 /* You can only use SlTableHeader if you are a CH_TABLE. */
1895 assert(_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
1896
1897 switch (_sl.action) {
1898 case SLA_LOAD_CHECK:
1899 case SLA_LOAD: {
1900 std::vector<SaveLoad> saveloads;
1901
1902 /* Build a key lookup mapping based on the available fields. */
1903 std::map<std::string, const SaveLoad *> key_lookup;
1904 for (auto &sld : slt) {
1905 if (!SlIsObjectValidInSavegame(sld)) continue;
1906
1907 /* Check that there is only one active SaveLoad for a given name. */
1908 assert(key_lookup.find(sld.name) == key_lookup.end());
1909 key_lookup[sld.name] = &sld;
1910 }
1911
1912 while (true) {
1913 uint8 type;
1914 SlSaveLoadConv(&type, SLE_UINT8);
1915 if (type == SLE_FILE_END) break;
1916
1917 std::string key;
1918 SlStdString(&key, SLE_STR);
1919
1920 auto sld_it = key_lookup.find(key);
1921 if (sld_it == key_lookup.end()) {
1922 /* SLA_LOADCHECK triggers this debug statement a lot and is perfectly normal. */
1923 Debug(sl, _sl.action == SLA_LOAD ? 2 : 6, "Field '{}' of type 0x{:02x} not found, skipping", key, type);
1924
1925 std::shared_ptr<SaveLoadHandler> handler = nullptr;
1926 SaveLoadType slt;
1927 switch (type & SLE_FILE_TYPE_MASK) {
1928 case SLE_FILE_STRING:
1929 /* Strings are always marked with SLE_FILE_HAS_LENGTH_FIELD, as they are a list of chars. */
1930 slt = SL_STR;
1931 break;
1932
1933 case SLE_FILE_STRUCT:
1934 /* Structs are always marked with SLE_FILE_HAS_LENGTH_FIELD as SL_STRUCT is seen as a list of 0/1 in length. */
1935 slt = SL_STRUCTLIST;
1936 handler = std::make_shared<SlSkipHandler>();
1937 break;
1938
1939 default:
1940 slt = (type & SLE_FILE_HAS_LENGTH_FIELD) ? SL_ARR : SL_VAR;
1941 break;
1942 }
1943
1944 /* We don't know this field, so read to nothing. */
1945 saveloads.push_back({key, slt, ((VarType)type & SLE_FILE_TYPE_MASK) | SLE_VAR_NULL, 1, SL_MIN_VERSION, SL_MAX_VERSION, 0, nullptr, 0, handler});
1946 continue;
1947 }
1948
1949 /* Validate the type of the field. If it is changed, the
1950 * savegame should have been bumped so we know how to do the
1951 * conversion. If this error triggers, that clearly didn't
1952 * happen and this is a friendly poke to the developer to bump
1953 * the savegame version and add conversion code. */
1954 uint8 correct_type = GetSavegameFileType(*sld_it->second);
1955 if (correct_type != type) {
1956 Debug(sl, 1, "Field type for '{}' was expected to be 0x{:02x} but 0x{:02x} was found", key, correct_type, type);
1957 SlErrorCorrupt("Field type is different than expected");
1958 }
1959 saveloads.push_back(*sld_it->second);
1960 }
1961
1962 for (auto &sld : saveloads) {
1963 if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1964 sld.handler->load_description = SlTableHeader(sld.handler->GetDescription());
1965 }
1966 }
1967
1968 return saveloads;
1969 }
1970
1971 case SLA_SAVE: {
1972 /* Automatically calculate the length? */
1973 if (_sl.need_length != NL_NONE) {
1974 SlSetLength(SlCalcTableHeader(slt));
1975 if (_sl.need_length == NL_CALCLENGTH) break;
1976 }
1977
1978 for (auto &sld : slt) {
1979 if (!SlIsObjectValidInSavegame(sld)) continue;
1980 /* Make sure we are not storing empty keys. */
1981 assert(!sld.name.empty());
1982
1983 uint8 type = GetSavegameFileType(sld);
1984 assert(type != SLE_FILE_END);
1985
1986 SlSaveLoadConv(&type, SLE_UINT8);
1987 SlStdString(const_cast<std::string *>(&sld.name), SLE_STR);
1988 }
1989
1990 /* Add an end-of-header marker. */
1991 uint8 type = SLE_FILE_END;
1992 SlSaveLoadConv(&type, SLE_UINT8);
1993
1994 /* After the table, write down any sub-tables we might have. */
1995 for (auto &sld : slt) {
1996 if (!SlIsObjectValidInSavegame(sld)) continue;
1997 if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
1998 /* SlCalcTableHeader already looks in sub-lists, so avoid the length being added twice. */
1999 NeedLength old_need_length = _sl.need_length;
2000 _sl.need_length = NL_NONE;
2001
2002 SlTableHeader(sld.handler->GetDescription());
2003
2004 _sl.need_length = old_need_length;
2005 }
2006 }
2007
2008 break;
2009 }
2010
2011 default: NOT_REACHED();
2012 }
2013
2014 return std::vector<SaveLoad>();
2015 }
2016
2030 std::vector<SaveLoad> SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
2031 {
2032 assert(_sl.action == SLA_LOAD || _sl.action == SLA_LOAD_CHECK);
2033 /* CH_TABLE / CH_SPARSE_TABLE always have a header. */
2034 if (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE) return SlTableHeader(slt);
2035
2036 std::vector<SaveLoad> saveloads;
2037
2038 /* Build a key lookup mapping based on the available fields. */
2039 std::map<std::string, std::vector<const SaveLoad *>> key_lookup;
2040 for (auto &sld : slt) {
2041 /* All entries should have a name; otherwise the entry should just be removed. */
2042 assert(!sld.name.empty());
2043
2044 key_lookup[sld.name].push_back(&sld);
2045 }
2046
2047 for (auto &slc : slct) {
2048 if (slc.name.empty()) {
2049 /* In old savegames there can be data we no longer care for. We
2050 * skip this by simply reading the amount of bytes indicated and
2051 * send those to /dev/null. */
2052 saveloads.push_back({"", SL_NULL, SLE_FILE_U8 | SLE_VAR_NULL, slc.length, slc.version_from, slc.version_to, 0, nullptr, 0, nullptr});
2053 } else {
2054 auto sld_it = key_lookup.find(slc.name);
2055 /* If this branch triggers, it means that an entry in the
2056 * SaveLoadCompat list is not mentioned in the SaveLoad list. Did
2057 * you rename a field in one and not in the other? */
2058 if (sld_it == key_lookup.end()) {
2059 /* This isn't an assert, as that leaves no information what
2060 * field was to blame. This way at least we have breadcrumbs. */
2061 Debug(sl, 0, "internal error: saveload compatibility field '{}' not found", slc.name);
2062 SlErrorCorrupt("Internal error with savegame compatibility");
2063 }
2064 for (auto &sld : sld_it->second) {
2065 saveloads.push_back(*sld);
2066 }
2067 }
2068 }
2069
2070 for (auto &sld : saveloads) {
2071 if (!SlIsObjectValidInSavegame(sld)) continue;
2072 if (sld.cmd == SL_STRUCTLIST || sld.cmd == SL_STRUCT) {
2073 sld.handler->load_description = SlCompatTableHeader(sld.handler->GetDescription(), sld.handler->GetCompatDescription());
2074 }
2075 }
2076
2077 return saveloads;
2078 }
2079
2084 void SlGlobList(const SaveLoadTable &slt)
2085 {
2086 SlObject(nullptr, slt);
2087 }
2088
2094 void SlAutolength(AutolengthProc *proc, void *arg)
2095 {
2096 size_t offs;
2097
2098 assert(_sl.action == SLA_SAVE);
2099
2100 /* Tell it to calculate the length */
2101 _sl.need_length = NL_CALCLENGTH;
2102 _sl.obj_len = 0;
2103 proc(arg);
2104
2105 /* Setup length */
2106 _sl.need_length = NL_WANTLENGTH;
2107 SlSetLength(_sl.obj_len);
2108
2109 offs = _sl.dumper->GetSize() + _sl.obj_len;
2110
2111 /* And write the stuff */
2112 proc(arg);
2113
2114 if (offs != _sl.dumper->GetSize()) SlErrorCorrupt("Invalid chunk size");
2115 }
2116
2117 void ChunkHandler::LoadCheck(size_t len) const
2118 {
2119 switch (_sl.block_mode) {
2120 case CH_TABLE:
2121 case CH_SPARSE_TABLE:
2122 SlTableHeader({});
2123 FALLTHROUGH;
2124 case CH_ARRAY:
2125 case CH_SPARSE_ARRAY:
2126 SlSkipArray();
2127 break;
2128 case CH_RIFF:
2129 SlSkipBytes(len);
2130 break;
2131 default:
2132 NOT_REACHED();
2133 }
2134 }
2135
2140 static void SlLoadChunk(const ChunkHandler &ch)
2141 {
2142 byte m = SlReadByte();
2143 size_t len;
2144 size_t endoffs;
2145
2146 _sl.block_mode = m & CH_TYPE_MASK;
2147 _sl.obj_len = 0;
2148 _sl.expect_table_header = (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
2149
2150 /* The header should always be at the start. Read the length; the
2151 * Load() should as first action process the header. */
2152 if (_sl.expect_table_header) {
2153 SlIterateArray();
2154 }
2155
2156 switch (_sl.block_mode) {
2157 case CH_TABLE:
2158 case CH_ARRAY:
2159 _sl.array_index = 0;
2160 ch.Load();
2161 if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
2162 break;
2163 case CH_SPARSE_TABLE:
2164 case CH_SPARSE_ARRAY:
2165 ch.Load();
2166 if (_next_offs != 0) SlErrorCorrupt("Invalid array length");
2167 break;
2168 case CH_RIFF:
2169 /* Read length */
2170 len = (SlReadByte() << 16) | ((m >> 4) << 24);
2171 len += SlReadUint16();
2172 _sl.obj_len = len;
2173 endoffs = _sl.reader->GetSize() + len;
2174 ch.Load();
2175 if (_sl.reader->GetSize() != endoffs) SlErrorCorrupt("Invalid chunk size");
2176 break;
2177 default:
2178 SlErrorCorrupt("Invalid chunk type");
2179 break;
2180 }
2181
2182 if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2183 }
2184
2190 static void SlLoadCheckChunk(const ChunkHandler &ch)
2191 {
2192 byte m = SlReadByte();
2193 size_t len;
2194 size_t endoffs;
2195
2196 _sl.block_mode = m & CH_TYPE_MASK;
2197 _sl.obj_len = 0;
2198 _sl.expect_table_header = (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
2199
2200 /* The header should always be at the start. Read the length; the
2201 * LoadCheck() should as first action process the header. */
2202 if (_sl.expect_table_header) {
2203 SlIterateArray();
2204 }
2205
2206 switch (_sl.block_mode) {
2207 case CH_TABLE:
2208 case CH_ARRAY:
2209 _sl.array_index = 0;
2210 ch.LoadCheck();
2211 break;
2212 case CH_SPARSE_TABLE:
2213 case CH_SPARSE_ARRAY:
2214 ch.LoadCheck();
2215 break;
2216 case CH_RIFF:
2217 /* Read length */
2218 len = (SlReadByte() << 16) | ((m >> 4) << 24);
2219 len += SlReadUint16();
2220 _sl.obj_len = len;
2221 endoffs = _sl.reader->GetSize() + len;
2222 ch.LoadCheck(len);
2223 if (_sl.reader->GetSize() != endoffs) SlErrorCorrupt("Invalid chunk size");
2224 break;
2225 default:
2226 SlErrorCorrupt("Invalid chunk type");
2227 break;
2228 }
2229
2230 if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2231 }
2232
2238 static void SlSaveChunk(const ChunkHandler &ch)
2239 {
2240 if (ch.type == CH_READONLY) return;
2241
2242 SlWriteUint32(ch.id);
2243 Debug(sl, 2, "Saving chunk {:c}{:c}{:c}{:c}", ch.id >> 24, ch.id >> 16, ch.id >> 8, ch.id);
2244
2245 _sl.block_mode = ch.type;
2246 _sl.expect_table_header = (_sl.block_mode == CH_TABLE || _sl.block_mode == CH_SPARSE_TABLE);
2247
2248 _sl.need_length = (_sl.expect_table_header || _sl.block_mode == CH_RIFF) ? NL_WANTLENGTH : NL_NONE;
2249
2250 switch (_sl.block_mode) {
2251 case CH_RIFF:
2252 ch.Save();
2253 break;
2254 case CH_TABLE:
2255 case CH_ARRAY:
2256 _sl.last_array_index = 0;
2257 SlWriteByte(_sl.block_mode);
2258 ch.Save();
2259 SlWriteArrayLength(0); // Terminate arrays
2260 break;
2261 case CH_SPARSE_TABLE:
2262 case CH_SPARSE_ARRAY:
2263 SlWriteByte(_sl.block_mode);
2264 ch.Save();
2265 SlWriteArrayLength(0); // Terminate arrays
2266 break;
2267 default: NOT_REACHED();
2268 }
2269
2270 if (_sl.expect_table_header) SlErrorCorrupt("Table chunk without header");
2271 }
2272
2274 static void SlSaveChunks()
2275 {
2276 for (auto &ch : ChunkHandlers()) {
2277 SlSaveChunk(ch);
2278 }
2279
2280 /* Terminator */
2281 SlWriteUint32(0);
2282 }
2283
2290 static const ChunkHandler *SlFindChunkHandler(uint32 id)
2291 {
2292 for (const ChunkHandler &ch : ChunkHandlers()) if (ch.id == id) return &ch;
2293 return nullptr;
2294 }
2295
2297 static void SlLoadChunks()
2298 {
2299 uint32 id;
2300 const ChunkHandler *ch;
2301
2302 for (id = SlReadUint32(); id != 0; id = SlReadUint32()) {
2303 Debug(sl, 2, "Loading chunk {:c}{:c}{:c}{:c}", id >> 24, id >> 16, id >> 8, id);
2304
2305 ch = SlFindChunkHandler(id);
2306 if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2307 SlLoadChunk(*ch);
2308 }
2309 }
2310
2312 static void SlLoadCheckChunks()
2313 {
2314 uint32 id;
2315 const ChunkHandler *ch;
2316
2317 for (id = SlReadUint32(); id != 0; id = SlReadUint32()) {
2318 Debug(sl, 2, "Loading chunk {:c}{:c}{:c}{:c}", id >> 24, id >> 16, id >> 8, id);
2319
2320 ch = SlFindChunkHandler(id);
2321 if (ch == nullptr) SlErrorCorrupt("Unknown chunk type");
2322 SlLoadCheckChunk(*ch);
2323 }
2324 }
2325
2327 static void SlFixPointers()
2328 {
2329 _sl.action = SLA_PTRS;
2330
2331 for (const ChunkHandler &ch : ChunkHandlers()) {
2332 Debug(sl, 3, "Fixing pointers for {:c}{:c}{:c}{:c}", ch.id >> 24, ch.id >> 16, ch.id >> 8, ch.id);
2333 ch.FixPointers();
2334 }
2335
2336 assert(_sl.action == SLA_PTRS);
2337 }
2338
2339
2341 struct FileReader : LoadFilter {
2342 FILE *file;
2343 long begin;
2344
2349 FileReader(FILE *file) : LoadFilter(nullptr), file(file), begin(ftell(file))
2350 {
2351 }
2352
2354 ~FileReader()
2355 {
2356 if (this->file != nullptr) fclose(this->file);
2357 this->file = nullptr;
2358
2359 /* Make sure we don't double free. */
2360 _sl.sf = nullptr;
2361 }
2362
2363 size_t Read(byte *buf, size_t size) override
2364 {
2365 /* We're in the process of shutting down, i.e. in "failure" mode. */
2366 if (this->file == nullptr) return 0;
2367
2368 return fread(buf, 1, size, this->file);
2369 }
2370
2371 void Reset() override
2372 {
2373 clearerr(this->file);
2374 if (fseek(this->file, this->begin, SEEK_SET)) {
2375 Debug(sl, 1, "Could not reset the file reading");
2376 }
2377 }
2378 };
2379
2381 struct FileWriter : SaveFilter {
2382 FILE *file;
2383
2388 FileWriter(FILE *file) : SaveFilter(nullptr), file(file)
2389 {
2390 }
2391
2393 ~FileWriter()
2394 {
2395 this->Finish();
2396
2397 /* Make sure we don't double free. */
2398 _sl.sf = nullptr;
2399 }
2400
2401 void Write(byte *buf, size_t size) override
2402 {
2403 /* We're in the process of shutting down, i.e. in "failure" mode. */
2404 if (this->file == nullptr) return;
2405
2406 if (fwrite(buf, 1, size, this->file) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
2407 }
2408
2409 void Finish() override
2410 {
2411 if (this->file != nullptr) fclose(this->file);
2412 this->file = nullptr;
2413 }
2414 };
2415
2416 /*******************************************
2417 ********** START OF LZO CODE **************
2418 *******************************************/
2419
2420 #ifdef WITH_LZO
2421 #include <lzo/lzo1x.h>
2422
2424 static const uint LZO_BUFFER_SIZE = 8192;
2425
2427 struct LZOLoadFilter : LoadFilter {
2432 LZOLoadFilter(LoadFilter *chain) : LoadFilter(chain)
2433 {
2434 if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2435 }
2436
2437 size_t Read(byte *buf, size_t ssize) override
2438 {
2439 assert(ssize >= LZO_BUFFER_SIZE);
2440
2441 /* Buffer size is from the LZO docs plus the chunk header size. */
2442 byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32) * 2];
2443 uint32 tmp[2];
2444 uint32 size;
2445 lzo_uint len = ssize;
2446
2447 /* Read header*/
2448 if (this->chain->Read((byte*)tmp, sizeof(tmp)) != sizeof(tmp)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE, "File read failed");
2449
2450 /* Check if size is bad */
2451 ((uint32*)out)[0] = size = tmp[1];
2452
2453 if (_sl_version != SL_MIN_VERSION) {
2454 tmp[0] = TO_BE32(tmp[0]);
2455 size = TO_BE32(size);
2456 }
2457
2458 if (size >= sizeof(out)) SlErrorCorrupt("Inconsistent size");
2459
2460 /* Read block */
2461 if (this->chain->Read(out + sizeof(uint32), size) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2462
2463 /* Verify checksum */
2464 if (tmp[0] != lzo_adler32(0, out, size + sizeof(uint32))) SlErrorCorrupt("Bad checksum");
2465
2466 /* Decompress */
2467 int ret = lzo1x_decompress_safe(out + sizeof(uint32) * 1, size, buf, &len, nullptr);
2468 if (ret != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2469 return len;
2470 }
2471 };
2472
2474 struct LZOSaveFilter : SaveFilter {
2480 LZOSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2481 {
2482 if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2483 }
2484
2485 void Write(byte *buf, size_t size) override
2486 {
2487 const lzo_bytep in = buf;
2488 /* Buffer size is from the LZO docs plus the chunk header size. */
2489 byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32) * 2];
2490 byte wrkmem[LZO1X_1_MEM_COMPRESS];
2491 lzo_uint outlen;
2492
2493 do {
2494 /* Compress up to LZO_BUFFER_SIZE bytes at once. */
2495 lzo_uint len = size > LZO_BUFFER_SIZE ? LZO_BUFFER_SIZE : (lzo_uint)size;
2496 lzo1x_1_compress(in, len, out + sizeof(uint32) * 2, &outlen, wrkmem);
2497 ((uint32*)out)[1] = TO_BE32((uint32)outlen);
2498 ((uint32*)out)[0] = TO_BE32(lzo_adler32(0, out + sizeof(uint32), outlen + sizeof(uint32)));
2499 this->chain->Write(out, outlen + sizeof(uint32) * 2);
2500
2501 /* Move to next data chunk. */
2502 size -= len;
2503 in += len;
2504 } while (size > 0);
2505 }
2506 };
2507
2508 #endif /* WITH_LZO */
2509
2510 /*********************************************
2511 ******** START OF NOCOMP CODE (uncompressed)*
2512 *********************************************/
2513
2515 struct NoCompLoadFilter : LoadFilter {
2520 NoCompLoadFilter(LoadFilter *chain) : LoadFilter(chain)
2521 {
2522 }
2523
2524 size_t Read(byte *buf, size_t size) override
2525 {
2526 return this->chain->Read(buf, size);
2527 }
2528 };
2529
2531 struct NoCompSaveFilter : SaveFilter {
2537 NoCompSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2538 {
2539 }
2540
2541 void Write(byte *buf, size_t size) override
2542 {
2543 this->chain->Write(buf, size);
2544 }
2545 };
2546
2547 /********************************************
2548 ********** START OF ZLIB CODE **************
2549 ********************************************/
2550
2551 #if defined(WITH_ZLIB)
2552 #include <zlib.h>
2553
2555 struct ZlibLoadFilter : LoadFilter {
2556 z_stream z;
2557 byte fread_buf[MEMORY_CHUNK_SIZE];
2558
2563 ZlibLoadFilter(LoadFilter *chain) : LoadFilter(chain)
2564 {
2565 memset(&this->z, 0, sizeof(this->z));
2566 if (inflateInit(&this->z) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2567 }
2568
2570 ~ZlibLoadFilter()
2571 {
2572 inflateEnd(&this->z);
2573 }
2574
2575 size_t Read(byte *buf, size_t size) override
2576 {
2577 this->z.next_out = buf;
2578 this->z.avail_out = (uint)size;
2579
2580 do {
2581 /* read more bytes from the file? */
2582 if (this->z.avail_in == 0) {
2583 this->z.next_in = this->fread_buf;
2584 this->z.avail_in = (uint)this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2585 }
2586
2587 /* inflate the data */
2588 int r = inflate(&this->z, 0);
2589 if (r == Z_STREAM_END) break;
2590
2591 if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "inflate() failed");
2592 } while (this->z.avail_out != 0);
2593
2594 return size - this->z.avail_out;
2595 }
2596 };
2597
2599 struct ZlibSaveFilter : SaveFilter {
2600 z_stream z;
2601
2607 ZlibSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2608 {
2609 memset(&this->z, 0, sizeof(this->z));
2610 if (deflateInit(&this->z, compression_level) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2611 }
2612
2614 ~ZlibSaveFilter()
2615 {
2616 deflateEnd(&this->z);
2617 }
2618
2625 void WriteLoop(byte *p, size_t len, int mode)
2626 {
2627 byte buf[MEMORY_CHUNK_SIZE]; // output buffer
2628 uint n;
2629 this->z.next_in = p;
2630 this->z.avail_in = (uInt)len;
2631 do {
2632 this->z.next_out = buf;
2633 this->z.avail_out = sizeof(buf);
2634
2642 int r = deflate(&this->z, mode);
2643
2644 /* bytes were emitted? */
2645 if ((n = sizeof(buf) - this->z.avail_out) != 0) {
2646 this->chain->Write(buf, n);
2647 }
2648 if (r == Z_STREAM_END) break;
2649
2650 if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "zlib returned error code");
2651 } while (this->z.avail_in || !this->z.avail_out);
2652 }
2653
2654 void Write(byte *buf, size_t size) override
2655 {
2656 this->WriteLoop(buf, size, 0);
2657 }
2658
2659 void Finish() override
2660 {
2661 this->WriteLoop(nullptr, 0, Z_FINISH);
2662 this->chain->Finish();
2663 }
2664 };
2665
2666 #endif /* WITH_ZLIB */
2667
2668 /********************************************
2669 ********** START OF LZMA CODE **************
2670 ********************************************/
2671
2672 #if defined(WITH_LIBLZMA)
2673 #include <lzma.h>
2674
2681 static const lzma_stream _lzma_init = LZMA_STREAM_INIT;
2682
2684 struct LZMALoadFilter : LoadFilter {
2685 lzma_stream lzma;
2686 byte fread_buf[MEMORY_CHUNK_SIZE];
2687
2692 LZMALoadFilter(LoadFilter *chain) : LoadFilter(chain), lzma(_lzma_init)
2693 {
2694 /* Allow saves up to 256 MB uncompressed */
2695 if (lzma_auto_decoder(&this->lzma, 1 << 28, 0) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2696 }
2697
2699 ~LZMALoadFilter()
2700 {
2701 lzma_end(&this->lzma);
2702 }
2703
2704 size_t Read(byte *buf, size_t size) override
2705 {
2706 this->lzma.next_out = buf;
2707 this->lzma.avail_out = size;
2708
2709 do {
2710 /* read more bytes from the file? */
2711 if (this->lzma.avail_in == 0) {
2712 this->lzma.next_in = this->fread_buf;
2713 this->lzma.avail_in = this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2714 }
2715
2716 /* inflate the data */
2717 lzma_ret r = lzma_code(&this->lzma, LZMA_RUN);
2718 if (r == LZMA_STREAM_END) break;
2719 if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2720 } while (this->lzma.avail_out != 0);
2721
2722 return size - this->lzma.avail_out;
2723 }
2724 };
2725
2727 struct LZMASaveFilter : SaveFilter {
2728 lzma_stream lzma;
2729
2735 LZMASaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain), lzma(_lzma_init)
2736 {
2737 if (lzma_easy_encoder(&this->lzma, compression_level, LZMA_CHECK_CRC32) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2738 }
2739
2741 ~LZMASaveFilter()
2742 {
2743 lzma_end(&this->lzma);
2744 }
2745
2752 void WriteLoop(byte *p, size_t len, lzma_action action)
2753 {
2754 byte buf[MEMORY_CHUNK_SIZE]; // output buffer
2755 size_t n;
2756 this->lzma.next_in = p;
2757 this->lzma.avail_in = len;
2758 do {
2759 this->lzma.next_out = buf;
2760 this->lzma.avail_out = sizeof(buf);
2761
2762 lzma_ret r = lzma_code(&this->lzma, action);
2763
2764 /* bytes were emitted? */
2765 if ((n = sizeof(buf) - this->lzma.avail_out) != 0) {
2766 this->chain->Write(buf, n);
2767 }
2768 if (r == LZMA_STREAM_END) break;
2769 if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2770 } while (this->lzma.avail_in || !this->lzma.avail_out);
2771 }
2772
2773 void Write(byte *buf, size_t size) override
2774 {
2775 this->WriteLoop(buf, size, LZMA_RUN);
2776 }
2777
2778 void Finish() override
2779 {
2780 this->WriteLoop(nullptr, 0, LZMA_FINISH);
2781 this->chain->Finish();
2782 }
2783 };
2784
2785 #endif /* WITH_LIBLZMA */
2786
2787 /*******************************************
2788 ************* END OF CODE *****************
2789 *******************************************/
2790
2792 struct SaveLoadFormat {
2793 const char *name;
2794 uint32 tag;
2795
2796 LoadFilter *(*init_load)(LoadFilter *chain);
2797 SaveFilter *(*init_write)(SaveFilter *chain, byte compression);
2798
2799 byte min_compression;
2800 byte default_compression;
2801 byte max_compression;
2802 };
2803
2805 static const SaveLoadFormat _saveload_formats[] = {
2806 #if defined(WITH_LZO)
2807 /* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
2808 {"lzo", TO_BE32X('OTTD'), CreateLoadFilter<LZOLoadFilter>, CreateSaveFilter<LZOSaveFilter>, 0, 0, 0},
2809 #else
2810 {"lzo", TO_BE32X('OTTD'), nullptr, nullptr, 0, 0, 0},
2811 #endif
2812 /* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
2813 {"none", TO_BE32X('OTTN'), CreateLoadFilter<NoCompLoadFilter>, CreateSaveFilter<NoCompSaveFilter>, 0, 0, 0},
2814 #if defined(WITH_ZLIB)
2815 /* After level 6 the speed reduction is significant (1.5x to 2.5x slower per level), but the reduction in filesize is
2816 * fairly insignificant (~1% for each step). Lower levels become ~5-10% bigger by each level than level 6 while level
2817 * 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
2818 {"zlib", TO_BE32X('OTTZ'), CreateLoadFilter<ZlibLoadFilter>, CreateSaveFilter<ZlibSaveFilter>, 0, 6, 9},
2819 #else
2820 {"zlib", TO_BE32X('OTTZ'), nullptr, nullptr, 0, 0, 0},
2821 #endif
2822 #if defined(WITH_LIBLZMA)
2823 /* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
2824 * Higher compression levels are possible, and might improve savegame size by up to 25%, but are also up to 10 times slower.
2825 * The next significant reduction in file size is at level 4, but that is already 4 times slower. Level 3 is primarily 50%
2826 * slower while not improving the filesize, while level 0 and 1 are faster, but don't reduce savegame size much.
2827 * It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
2828 {"lzma", TO_BE32X('OTTX'), CreateLoadFilter<LZMALoadFilter>, CreateSaveFilter<LZMASaveFilter>, 0, 2, 9},
2829 #else
2830 {"lzma", TO_BE32X('OTTX'), nullptr, nullptr, 0, 0, 0},
2831 #endif
2832 };
2833
2841 static const SaveLoadFormat *GetSavegameFormat(const std::string &full_name, byte *compression_level)
2842 {
2843 const SaveLoadFormat *def = lastof(_saveload_formats);
2844
2845 /* find default savegame format, the highest one with which files can be written */
2846 while (!def->init_write) def--;
2847
2848 if (!full_name.empty()) {
2849 /* Get the ":..." of the compression level out of the way */
2850 size_t separator = full_name.find(':');
2851 bool has_comp_level = separator != std::string::npos;
2852 const std::string name(full_name, 0, has_comp_level ? separator : full_name.size());
2853
2854 for (const SaveLoadFormat *slf = &_saveload_formats[0]; slf != endof(_saveload_formats); slf++) {
2855 if (slf->init_write != nullptr && name.compare(slf->name) == 0) {
2856 *compression_level = slf->default_compression;
2857 if (has_comp_level) {
2858 const std::string complevel(full_name, separator + 1);
2859
2860 /* Get the level and determine whether all went fine. */
2861 size_t processed;
2862 long level = std::stol(complevel, &processed, 10);
2863 if (processed == 0 || level != Clamp(level, slf->min_compression, slf->max_compression)) {
2864 SetDParamStr(0, complevel);
2865 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_LEVEL, WL_CRITICAL);
2866 } else {
2867 *compression_level = level;
2868 }
2869 }
2870 return slf;
2871 }
2872 }
2873
2874 SetDParamStr(0, name);
2875 SetDParamStr(1, def->name);
2876 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM, WL_CRITICAL);
2877 }
2878 *compression_level = def->default_compression;
2879 return def;
2880 }
2881
2882 /* actual loader/saver function */
2883 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
2884 extern bool AfterLoadGame();
2885 extern bool LoadOldSaveGame(const std::string &file);
2886
2890 static void ResetSaveloadData()
2891 {
2892 ResetTempEngineData();
2893 ResetLabelMaps();
2894 ResetOldWaypoints();
2895 }
2896
2900 static inline void ClearSaveLoadState()
2901 {
2902 delete _sl.dumper;
2903 _sl.dumper = nullptr;
2904
2905 delete _sl.sf;
2906 _sl.sf = nullptr;
2907
2908 delete _sl.reader;
2909 _sl.reader = nullptr;
2910
2911 delete _sl.lf;
2912 _sl.lf = nullptr;
2913 }
2914
2916 static void SaveFileStart()
2917 {
2918 SetMouseCursorBusy(true);
2919
2920 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SAVELOAD_START);
2921 _sl.saveinprogress = true;
2922 }
2923
2925 static void SaveFileDone()
2926 {
2927 SetMouseCursorBusy(false);
2928
2929 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SAVELOAD_FINISH);
2930 _sl.saveinprogress = false;
2931
2932 #ifdef __EMSCRIPTEN__
2933 EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
2934 #endif
2935 }
2936
2938 void SetSaveLoadError(StringID str)
2939 {
2940 _sl.error_str = str;
2941 }
2942
2944 const char *GetSaveLoadErrorString()
2945 {
2946 SetDParam(0, _sl.error_str);
2947 SetDParamStr(1, _sl.extra_msg);
2948
2949 static char err_str[512];
2950 GetString(err_str, _sl.action == SLA_SAVE ? STR_ERROR_GAME_SAVE_FAILED : STR_ERROR_GAME_LOAD_FAILED, lastof(err_str));
2951 return err_str;
2952 }
2953
2955 static void SaveFileError()
2956 {
2957 SetDParamStr(0, GetSaveLoadErrorString());
2958 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
2959 SaveFileDone();
2960 }
2961
2966 static SaveOrLoadResult SaveFileToDisk(bool threaded)
2967 {
2968 try {
2969 byte compression;
2970 const SaveLoadFormat *fmt = GetSavegameFormat(_savegame_format, &compression);
2971
2972 /* We have written our stuff to memory, now write it to file! */
2973 uint32 hdr[2] = { fmt->tag, TO_BE32(SAVEGAME_VERSION << 16) };
2974 _sl.sf->Write((byte*)hdr, sizeof(hdr));
2975
2976 _sl.sf = fmt->init_write(_sl.sf, compression);
2977 _sl.dumper->Flush(_sl.sf);
2978
2979 ClearSaveLoadState();
2980
2981 if (threaded) SetAsyncSaveFinish(SaveFileDone);
2982
2983 return SL_OK;
2984 } catch (...) {
2985 ClearSaveLoadState();
2986
2987 AsyncSaveFinishProc asfp = SaveFileDone;
2988
2989 /* We don't want to shout when saving is just
2990 * cancelled due to a client disconnecting. */
2991 if (_sl.error_str != STR_NETWORK_ERROR_LOSTCONNECTION) {
2992 /* Skip the "colour" character */
2993 Debug(sl, 0, "{}", GetSaveLoadErrorString() + 3);
2994 asfp = SaveFileError;
2995 }
2996
2997 if (threaded) {
2998 SetAsyncSaveFinish(asfp);
2999 } else {
3000 asfp();
3001 }
3002 return SL_ERROR;
3003 }
3004 }
3005
3006 void WaitTillSaved()
3007 {
3008 if (!_save_thread.joinable()) return;
3009
3010 _save_thread.join();
3011
3012 /* Make sure every other state is handled properly as well. */
3013 ProcessAsyncSaveFinish();
3014 }
3015
3024 static SaveOrLoadResult DoSave(SaveFilter *writer, bool threaded)
3025 {
3026 assert(!_sl.saveinprogress);
3027
3028 _sl.dumper = new MemoryDumper();
3029 _sl.sf = writer;
3030
3031 _sl_version = SAVEGAME_VERSION;
3032
3033 SaveViewportBeforeSaveGame();
3034 SlSaveChunks();
3035
3036 SaveFileStart();
3037
3038 if (!threaded || !StartNewThread(&_save_thread, "ottd:savegame", &SaveFileToDisk, true)) {
3039 if (threaded) Debug(sl, 1, "Cannot create savegame thread, reverting to single-threaded mode...");
3040
3041 SaveOrLoadResult result = SaveFileToDisk(false);
3042 SaveFileDone();
3043
3044 return result;
3045 }
3046
3047 return SL_OK;
3048 }
3049
3056 SaveOrLoadResult SaveWithFilter(SaveFilter *writer, bool threaded)
3057 {
3058 try {
3059 _sl.action = SLA_SAVE;
3060 return DoSave(writer, threaded);
3061 } catch (...) {
3062 ClearSaveLoadState();
3063 return SL_ERROR;
3064 }
3065 }
3066
3073 static SaveOrLoadResult DoLoad(LoadFilter *reader, bool load_check)
3074 {
3075 _sl.lf = reader;
3076
3077 if (load_check) {
3078 /* Clear previous check data */
3079 _load_check_data.Clear();
3080 /* Mark SL_LOAD_CHECK as supported for this savegame. */
3081 _load_check_data.checkable = true;
3082 }
3083
3084 uint32 hdr[2];
3085 if (_sl.lf->Read((byte*)hdr, sizeof(hdr)) != sizeof(hdr)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3086
3087 /* see if we have any loader for this type. */
3088 const SaveLoadFormat *fmt = _saveload_formats;
3089 for (;;) {
3090 /* No loader found, treat as version 0 and use LZO format */
3091 if (fmt == endof(_saveload_formats)) {
3092 Debug(sl, 0, "Unknown savegame type, trying to load it as the buggy format");
3093 _sl.lf->Reset();
3094 _sl_version = SL_MIN_VERSION;
3095 _sl_minor_version = 0;
3096
3097 /* Try to find the LZO savegame format; it uses 'OTTD' as tag. */
3098 fmt = _saveload_formats;
3099 for (;;) {
3100 if (fmt == endof(_saveload_formats)) {
3101 /* Who removed LZO support? */
3102 NOT_REACHED();
3103 }
3104 if (fmt->tag == TO_BE32X('OTTD')) break;
3105 fmt++;
3106 }
3107 break;
3108 }
3109
3110 if (fmt->tag == hdr[0]) {
3111 /* check version number */
3112 _sl_version = (SaveLoadVersion)(TO_BE32(hdr[1]) >> 16);
3113 /* Minor is not used anymore from version 18.0, but it is still needed
3114 * in versions before that (4 cases) which can't be removed easy.
3115 * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */
3116 _sl_minor_version = (TO_BE32(hdr[1]) >> 8) & 0xFF;
3117
3118 Debug(sl, 1, "Loading savegame version {}", _sl_version);
3119
3120 /* Is the version higher than the current? */
3121 if (_sl_version > SAVEGAME_VERSION) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME);
3122 if (_sl_version >= SLV_START_PATCHPACKS && _sl_version <= SLV_END_PATCHPACKS) SlError(STR_GAME_SAVELOAD_ERROR_PATCHPACK);
3123 break;
3124 }
3125
3126 fmt++;
3127 }
3128
3129 /* loader for this savegame type is not implemented? */
3130 if (fmt->init_load == nullptr) {
3131 char err_str[64];
3132 seprintf(err_str, lastof(err_str), "Loader for '%s' is not available.", fmt->name);
3133 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, err_str);
3134 }
3135
3136 _sl.lf = fmt->init_load(_sl.lf);
3137 _sl.reader = new ReadBuffer(_sl.lf);
3138 _next_offs = 0;
3139
3140 if (!load_check) {
3141 ResetSaveloadData();
3142
3143 /* Old maps were hardcoded to 256x256 and thus did not contain
3144 * any mapsize information. Pre-initialize to 256x256 to not to
3145 * confuse old games */
3146 InitializeGame(256, 256, true, true);
3147
3148 GamelogReset();
3149
3150 if (IsSavegameVersionBefore(SLV_4)) {
3151 /*
3152 * NewGRFs were introduced between 0.3,4 and 0.3.5, which both
3153 * shared savegame version 4. Anything before that 'obviously'
3154 * does not have any NewGRFs. Between the introduction and
3155 * savegame version 41 (just before 0.5) the NewGRF settings
3156 * were not stored in the savegame and they were loaded by
3157 * using the settings from the main menu.
3158 * So, to recap:
3159 * - savegame version < 4: do not load any NewGRFs.
3160 * - savegame version >= 41: load NewGRFs from savegame, which is
3161 * already done at this stage by
3162 * overwriting the main menu settings.
3163 * - other savegame versions: use main menu settings.
3164 *
3165 * This means that users *can* crash savegame version 4..40
3166 * savegames if they set incompatible NewGRFs in the main menu,
3167 * but can't crash anymore for savegame version < 4 savegames.
3168 *
3169 * Note: this is done here because AfterLoadGame is also called
3170 * for TTO/TTD/TTDP savegames which have their own NewGRF logic.
3171 */
3172 ClearGRFConfigList(&_grfconfig);
3173 }
3174 }
3175
3176 if (load_check) {
3177 /* Load chunks into _load_check_data.
3178 * No pools are loaded. References are not possible, and thus do not need resolving. */
3179 SlLoadCheckChunks();
3180 } else {
3181 /* Load chunks and resolve references */
3182 SlLoadChunks();
3183 SlFixPointers();
3184 }
3185
3186 ClearSaveLoadState();
3187
3188 _savegame_type = SGT_OTTD;
3189
3190 if (load_check) {
3191 /* The only part from AfterLoadGame() we need */
3192 _load_check_data.grf_compatibility = IsGoodGRFConfigList(_load_check_data.grfconfig);
3193 } else {
3194 GamelogStartAction(GLAT_LOAD);
3195
3196 /* After loading fix up savegame for any internal changes that
3197 * might have occurred since then. If it fails, load back the old game. */
3198 if (!AfterLoadGame()) {
3199 GamelogStopAction();
3200 return SL_REINIT;
3201 }
3202
3203 GamelogStopAction();
3204 }
3205
3206 return SL_OK;
3207 }
3208
3214 SaveOrLoadResult LoadWithFilter(LoadFilter *reader)
3215 {
3216 try {
3217 _sl.action = SLA_LOAD;
3218 return DoLoad(reader, false);
3219 } catch (...) {
3220 ClearSaveLoadState();
3221 return SL_REINIT;
3222 }
3223 }
3224
3234 SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
3235 {
3236 /* An instance of saving is already active, so don't go saving again */
3237 if (_sl.saveinprogress && fop == SLO_SAVE && dft == DFT_GAME_FILE && threaded) {
3238 /* if not an autosave, but a user action, show error message */
3239 if (!_do_autosave) ShowErrorMessage(STR_ERROR_SAVE_STILL_IN_PROGRESS, INVALID_STRING_ID, WL_ERROR);
3240 return SL_OK;
3241 }
3242 WaitTillSaved();
3243
3244 try {
3245 /* Load a TTDLX or TTDPatch game */
3246 if (fop == SLO_LOAD && dft == DFT_OLD_GAME_FILE) {
3247 ResetSaveloadData();
3248
3249 InitializeGame(256, 256, true, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
3250
3251 /* TTD/TTO savegames have no NewGRFs, TTDP savegame have them
3252 * and if so a new NewGRF list will be made in LoadOldSaveGame.
3253 * Note: this is done here because AfterLoadGame is also called
3254 * for OTTD savegames which have their own NewGRF logic. */
3255 ClearGRFConfigList(&_grfconfig);
3256 GamelogReset();
3257 if (!LoadOldSaveGame(filename)) return SL_REINIT;
3258 _sl_version = SL_MIN_VERSION;
3259 _sl_minor_version = 0;
3260 GamelogStartAction(GLAT_LOAD);
3261 if (!AfterLoadGame()) {
3262 GamelogStopAction();
3263 return SL_REINIT;
3264 }
3265 GamelogStopAction();
3266 return SL_OK;
3267 }
3268
3269 assert(dft == DFT_GAME_FILE);
3270 switch (fop) {
3271 case SLO_CHECK:
3272 _sl.action = SLA_LOAD_CHECK;
3273 break;
3274
3275 case SLO_LOAD:
3276 _sl.action = SLA_LOAD;
3277 break;
3278
3279 case SLO_SAVE:
3280 _sl.action = SLA_SAVE;
3281 break;
3282
3283 default: NOT_REACHED();
3284 }
3285
3286 FILE *fh = (fop == SLO_SAVE) ? FioFOpenFile(filename, "wb", sb) : FioFOpenFile(filename, "rb", sb);
3287
3288 /* Make it a little easier to load savegames from the console */
3289 if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SAVE_DIR);
3290 if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", BASE_DIR);
3291 if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SCENARIO_DIR);
3292
3293 if (fh == nullptr) {
3294 SlError(fop == SLO_SAVE ? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE : STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3295 }
3296
3297 if (fop == SLO_SAVE) { // SAVE game
3298 Debug(desync, 1, "save: {:08x}; {:02x}; {}", _date, _date_fract, filename);
3299 if (_network_server || !_settings_client.gui.threaded_saves) threaded = false;
3300
3301 return DoSave(new FileWriter(fh), threaded);
3302 }
3303
3304 /* LOAD game */
3305 assert(fop == SLO_LOAD || fop == SLO_CHECK);
3306 Debug(desync, 1, "load: {}", filename);
3307 return DoLoad(new FileReader(fh), fop == SLO_CHECK);
3308 } catch (...) {
3309 /* This code may be executed both for old and new save games. */
3310 ClearSaveLoadState();
3311
3312 /* Skip the "colour" character */
3313 if (fop != SLO_CHECK) Debug(sl, 0, "{}", GetSaveLoadErrorString() + 3);
3314
3315 /* A saver/loader exception!! reinitialize all variables to prevent crash! */
3316 return (fop == SLO_LOAD) ? SL_REINIT : SL_ERROR;
3317 }
3318 }
3319
3325 void DoAutoOrNetsave(FiosNumberedSaveName &counter)
3326 {
3327 char buf[MAX_PATH];
3328
3329 if (_settings_client.gui.keep_all_autosave) {
3330 GenerateDefaultSaveName(buf, lastof(buf));
3331 strecat(buf, counter.Extension().c_str(), lastof(buf));
3332 } else {
3333 strecpy(buf, counter.Filename().c_str(), lastof(buf));
3334 }
3335
3336 Debug(sl, 2, "Autosaving to '{}'", buf);
3337 if (SaveOrLoad(buf, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR) != SL_OK) {
3338 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
3339 }
3340 }
3341
3342
3344 void DoExitSave()
3345 {
3346 SaveOrLoad("exit.sav", SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR);
3347 }
3348
3354 void GenerateDefaultSaveName(char *buf, const char *last)
3355 {
3356 /* Check if we have a name for this map, which is the name of the first
3357 * available company. When there's no company available we'll use
3358 * 'Spectator' as "company" name. */
3359 CompanyID cid = _local_company;
3360 if (!Company::IsValidID(cid)) {
3361 for (const Company *c : Company::Iterate()) {
3362 cid = c->index;
3363 break;
3364 }
3365 }
3366
3367 SetDParam(0, cid);
3368
3369 /* Insert current date */
3370 switch (_settings_client.gui.date_format_in_default_names) {
3371 case 0: SetDParam(1, STR_JUST_DATE_LONG); break;
3372 case 1: SetDParam(1, STR_JUST_DATE_TINY); break;
3373 case 2: SetDParam(1, STR_JUST_DATE_ISO); break;
3374 default: NOT_REACHED();
3375 }
3376 SetDParam(2, _date);
3377
3378 /* Get the correct string (special string for when there's not company) */
3379 GetString(buf, !Company::IsValidID(cid) ? STR_SAVEGAME_NAME_SPECTATOR : STR_SAVEGAME_NAME_DEFAULT, last);
3380 SanitizeFilename(buf);
3381 }
3382
3387 void FileToSaveLoad::SetMode(FiosType ft)
3388 {
3389 this->SetMode(SLO_LOAD, GetAbstractFileType(ft), GetDetailedFileType(ft));
3390 }
3391
3398 void FileToSaveLoad::SetMode(SaveLoadOperation fop, AbstractFileType aft, DetailedFileType dft)
3399 {
3400 if (aft == FT_INVALID || aft == FT_NONE) {
3401 this->file_op = SLO_INVALID;
3402 this->detail_ftype = DFT_INVALID;
3403 this->abstract_ftype = FT_INVALID;
3404 return;
3405 }
3406
3407 this->file_op = fop;
3408 this->detail_ftype = dft;
3409 this->abstract_ftype = aft;
3410 }
3411
3416 void FileToSaveLoad::SetName(const char *name)
3417 {
3418 this->name = name;
3419 }
3420
3425 void FileToSaveLoad::SetTitle(const char *title)
3426 {
3427 strecpy(this->title, title, lastof(this->title));
3428 }
3429
3430 SaveLoadTable SaveLoadHandler::GetLoadDescription() const
3431 {
3432 assert(this->load_description.has_value());
3433 return *this->load_description;
3434 }
FileToSaveLoad::title
char title[255]
Internal name of the game.
Definition: saveload.h:364
SL_NULL
@ SL_NULL
Save null-bytes and load to nowhere.
Definition: saveload.h:653
ZlibLoadFilter::fread_buf
byte fread_buf[MEMORY_CHUNK_SIZE]
Buffer for reading from the file.
Definition: saveload.cpp:2559
SlLoadChunks
static void SlLoadChunks()
Load all chunks.
Definition: saveload.cpp:2297
SlCalcTableHeader
static size_t SlCalcTableHeader(const SaveLoadTable &slt)
Calculate the size of the table header.
Definition: saveload.cpp:1566
ResetSaveloadData
static void ResetSaveloadData()
Clear temporary data that is passed between various saveload phases.
Definition: saveload.cpp:2890
IsVariableSizeRight
static bool IsVariableSizeRight(const SaveLoad &sld)
Check whether the variable size of the variable in the saveload configuration matches with the actual...
Definition: saveload.cpp:1658
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:1397
SetMouseCursorBusy
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
Definition: gfx.cpp:1908
SaveLoad::version_to
SaveLoadVersion version_to
Save/load the variable before this savegame version.
Definition: saveload.h:665
SaveLoadFormat::init_write
SaveFilter *(* init_write)(SaveFilter *chain, byte compression)
Constructor for the save filter.
Definition: saveload.cpp:2799
FileWriter::FileWriter
FileWriter(FILE *file)
Create the file writer, so it writes to a specific file.
Definition: saveload.cpp:2388
SlIsObjectValidInSavegame
static bool SlIsObjectValidInSavegame(const SaveLoad &sld)
Are we going to save this object or not?
Definition: saveload.cpp:1556
LZMASaveFilter::lzma
lzma_stream lzma
Stream state that we are writing to.
Definition: saveload.cpp:2728
SLV_69
@ SLV_69
69 10319
Definition: saveload.h:129
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:3252
LZO_BUFFER_SIZE
static const uint LZO_BUFFER_SIZE
Buffer size for the LZO compressor.
Definition: saveload.cpp:2424
REF_ORDER
@ REF_ORDER
Load/save a reference to an order.
Definition: saveload.h:541
SaveLoadType
SaveLoadType
Type of data saved.
Definition: saveload.h:638
SlDeque
static void SlDeque(void *deque, VarType conv)
Save/load a std::deque.
Definition: saveload.cpp:1497
SLV_169
@ SLV_169
169 23816
Definition: saveload.h:249
SlLoadChunk
static void SlLoadChunk(const ChunkHandler &ch)
Load a chunk of data (eg vehicles, stations, etc.)
Definition: saveload.cpp:2140
LoadCheckData::checkable
bool checkable
True if the savegame could be checked by SL_LOAD_CHECK. (Old savegames are not checkable....
Definition: fios.h:32
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:2938
ZlibLoadFilter::~ZlibLoadFilter
~ZlibLoadFilter()
Clean everything up.
Definition: saveload.cpp:2572
Pool::PoolItem<&_orderlist_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:337
SAVE_DIR
@ SAVE_DIR
Base directory for all savegames.
Definition: fileio_type.h:110
SaveLoadFormat::min_compression
byte min_compression
the minimum compression level of this format
Definition: saveload.cpp:2801
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:1182
SGT_OTTD
@ SGT_OTTD
OTTD savegame.
Definition: saveload.h:377
SVS_ALLOW_NEWLINE
@ SVS_ALLOW_NEWLINE
Allow newlines.
Definition: string_type.h:52
LinkGraph
A connected component of a link graph.
Definition: linkgraph.h:39
_save_thread
static std::thread _save_thread
The thread we're using to compress and write a savegame.
Definition: saveload.cpp:392
SLE_VAR_STR
@ SLE_VAR_STR
string pointer
Definition: saveload.h:595
GB
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
LZMALoadFilter::LZMALoadFilter
LZMALoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2692
GetVarFileType
static VarType GetVarFileType(VarType type)
Get the FileType of a setting.
Definition: saveload.h:1080
LZMASaveFilter::LZMASaveFilter
LZMASaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2735
NoCompLoadFilter
Filter without any compression.
Definition: saveload.cpp:2515
_sl_minor_version
byte _sl_minor_version
the minor savegame version, DO NOT USE!
Definition: saveload.cpp:67
GLAT_LOAD
@ GLAT_LOAD
Game loaded.
Definition: gamelog.h:18
LZMALoadFilter::fread_buf
byte fread_buf[MEMORY_CHUNK_SIZE]
Buffer for reading from the file.
Definition: saveload.cpp:2686
SLA_SAVE
@ SLA_SAVE
saving
Definition: saveload.cpp:74
RemapOldStringID
StringID RemapOldStringID(StringID s)
Remap a string ID from the old format to the new format.
Definition: strings_sl.cpp:29
CSleep
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:23
SL_MIN_VERSION
@ SL_MIN_VERSION
First savegame version.
Definition: saveload.h:35
SaveLoadFormat::init_load
LoadFilter *(* init_load)(LoadFilter *chain)
Constructor for the load filter.
Definition: saveload.cpp:2798
REF_TOWN
@ REF_TOWN
Load/save a reference to a town.
Definition: saveload.h:544
DoExitSave
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:3344
ClearGRFConfigList
void ClearGRFConfigList(GRFConfig **config)
Clear a GRF Config list, freeing all nodes.
Definition: newgrf_config.cpp:400
NoCompLoadFilter::NoCompLoadFilter
NoCompLoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2522
GUISettings::date_format_in_default_names
uint8 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:142
NoCompSaveFilter::NoCompSaveFilter
NoCompSaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2537
SL_STR
@ SL_STR
Save/load a string.
Definition: saveload.h:643
REF_ROADSTOPS
@ REF_ROADSTOPS
Load/save a reference to a bus/truck stop.
Definition: saveload.h:546
FileToSaveLoad::SetTitle
void SetTitle(const char *title)
Set the title of the file.
Definition: saveload.cpp:3425
SLE_FILE_END
@ SLE_FILE_END
Used to mark end-of-header in tables.
Definition: saveload.h:566
FileReader::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2363
Station
Station data structure.
Definition: station_base.h:454
SlSkipArray
void SlSkipArray()
Skip an array or sparse array.
Definition: saveload.cpp:712
LinkGraphJob
Class for calculation jobs to be run on link graphs.
Definition: linkgraphjob.h:30
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:3234
_date_fract
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:29
_network_server
bool _network_server
network-server is active
Definition: network.cpp:59
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:1152
FileToSaveLoad::name
std::string name
Name of the file.
Definition: saveload.h:363
str_fix_scc_encoded
void str_fix_scc_encoded(char *str, const char *last)
Scan the string for old values of SCC_ENCODED and fix it to it's new, static value.
Definition: string.cpp:187
FileReader::begin
long begin
The begin of the file.
Definition: saveload.cpp:2343
SaveLoad::size
size_t size
The sizeof size.
Definition: saveload.h:666
_load_check_data
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition: fios_gui.cpp:39
LZOLoadFilter::LZOLoadFilter
LZOLoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2432
AfterLoadGame
bool AfterLoadGame()
Perform a (large) amount of savegame conversion magic in order to load older savegames and to fill th...
Definition: afterload.cpp:563
SLF_ALLOW_NEWLINE
@ SLF_ALLOW_NEWLINE
Allow new lines in the strings.
Definition: saveload.h:632
ZlibLoadFilter::ZlibLoadFilter
ZlibLoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2565
SlSaveChunks
static void SlSaveChunks()
Save all chunks.
Definition: saveload.cpp:2274
SLA_LOAD_CHECK
@ SLA_LOAD_CHECK
partial loading into _load_check_data
Definition: saveload.cpp:77
SLO_CHECK
@ SLO_CHECK
Load file for checking and/or preview.
Definition: fileio_type.h:48
SLE_STR
#define SLE_STR(base, variable, type, length)
Storage of a string in every savegame version.
Definition: saveload.h:804
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
MemoryDumper::MemoryDumper
MemoryDumper()
Initialise our variables.
Definition: saveload.cpp:137
_do_autosave
bool _do_autosave
are we doing an autosave at the moment?
Definition: saveload.cpp:69
LZOSaveFilter::LZOSaveFilter
LZOSaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2480
MemoryDumper::GetSize
size_t GetSize() const
Get the size of the memory dump made so far.
Definition: saveload.cpp:187
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:359
LoadCheckData::grfconfig
GRFConfig * grfconfig
NewGrf configuration from save.
Definition: fios.h:43
FileToSaveLoad::SetName
void SetName(const char *name)
Set the name of the file.
Definition: saveload.cpp:3416
SaveLoadFormat::max_compression
byte max_compression
the maximum compression level of this format
Definition: saveload.cpp:2803
SLE_VAR_NULL
@ SLE_VAR_NULL
useful to write zeros in savegame.
Definition: saveload.h:593
LZOLoadFilter::Read
size_t Read(byte *buf, size_t ssize) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2437
GetSavegameFileType
static uint8 GetSavegameFileType(const SaveLoad &sld)
Return the type as saved/loaded inside the savegame.
Definition: saveload.cpp:585
SaveLoadHandler::GetLoadDescription
SaveLoadTable GetLoadDescription() const
Get the description for how to load the chunk.
Definition: saveload.cpp:3430
ChunkHandler::type
ChunkType type
Type of the chunk.
Definition: saveload.h:414
SaveLoad::length
uint16 length
(Conditional) length of the variable (eg. arrays) (max array size is 65536 elements).
Definition: saveload.h:663
ReadBuffer
A buffer for reading (and buffering) savegame data.
Definition: saveload.cpp:90
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:218
AUTOSAVE_DIR
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
Definition: fileio_type.h:111
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:53
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:308
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:209
SLA_LOAD
@ SLA_LOAD
loading
Definition: saveload.cpp:73
SaveLoadParams::reader
ReadBuffer * reader
Savegame reading buffer.
Definition: saveload.cpp:207
ZlibLoadFilter
Filter using Zlib compression.
Definition: saveload.cpp:2555
LoadWithFilter
SaveOrLoadResult LoadWithFilter(LoadFilter *reader)
Load the game using a (reader) filter.
Definition: saveload.cpp:3214
ChunkHandler
Handlers and description of chunk.
Definition: saveload.h:412
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:224
SaveLoad::conv
VarType conv
Type of the variable to be saved; this field combines both FileVarType and MemVarType.
Definition: saveload.h:662
LZMASaveFilter::WriteLoop
void WriteLoop(byte *p, size_t len, lzma_action action)
Helper loop for writing the data.
Definition: saveload.cpp:2752
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:644
SaveLoadFormat::default_compression
byte default_compression
the default compression level of this format
Definition: saveload.cpp:2802
SaveLoadAction
SaveLoadAction
What are we currently doing?
Definition: saveload.cpp:72
LoadFilter::Reset
virtual void Reset()
Reset this filter to read from the beginning of the file.
Definition: saveload_filter.h:43
SaveLoadParams::sf
SaveFilter * sf
Filter to write the savegame to.
Definition: saveload.cpp:205
SaveLoadHandler
Handler for saving/loading an object to/from disk.
Definition: saveload.h:461
SlSkipHandler::Load
void Load(void *object) const override
Load the object from disk.
Definition: saveload.cpp:1862
SetDParam
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:196
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:956
NL_NONE
@ NL_NONE
not working in NeedLength mode
Definition: saveload.cpp:81
AsyncSaveFinishProc
void(* AsyncSaveFinishProc)()
Callback for when the savegame loading is finished.
Definition: saveload.cpp:390
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:724
NoCompLoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2526
ZlibSaveFilter::z
z_stream z
Stream state we are writing to.
Definition: saveload.cpp:2600
SlReadSimpleGamma
static uint SlReadSimpleGamma()
Read in the header descriptor of an object or an array.
Definition: saveload.cpp:485
SLE_FILE_TYPE_MASK
@ SLE_FILE_TYPE_MASK
Mask to get the file-type (and not any flags).
Definition: saveload.h:580
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
Definition: error_gui.cpp:377
saveload_filter.h
ReadBuffer::reader
LoadFilter * reader
The filter used to actually read.
Definition: saveload.cpp:94
MemoryDumper::buf
byte * buf
Buffer we're going to write to.
Definition: saveload.cpp:133
SlGlobList
void SlGlobList(const SaveLoadTable &slt)
Save or Load (a list of) global variables.
Definition: saveload.cpp:2084
NoCompSaveFilter
Filter without any compression.
Definition: saveload.cpp:2531
REF_STATION
@ REF_STATION
Load/save a reference to a station.
Definition: saveload.h:543
LZMALoadFilter
Filter without any compression.
Definition: saveload.cpp:2684
SLE_VAR_STRB
@ SLE_VAR_STRB
string (with pre-allocated buffer)
Definition: saveload.h:594
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:621
AbstractFileType
AbstractFileType
The different abstract types of files that the system knows about.
Definition: fileio_type.h:16
LoadFilter::Read
virtual size_t Read(byte *buf, size_t len)=0
Read a given number of bytes from the savegame.
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:1228
SaveLoadFormat
The format for a reader/writer type of a savegame.
Definition: saveload.cpp:2792
FileToSaveLoad::abstract_ftype
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Definition: saveload.h:362
ReadBuffer::buf
byte buf[MEMORY_CHUNK_SIZE]
Buffer we're going to read from.
Definition: saveload.cpp:91
SaveLoadParams::block_mode
byte block_mode
???
Definition: saveload.cpp:197
FileWriter::file
FILE * file
The file to write to.
Definition: saveload.cpp:2382
SVS_ALLOW_CONTROL_CODE
@ SVS_ALLOW_CONTROL_CODE
Allow the special control codes.
Definition: string_type.h:53
BASE_DIR
@ BASE_DIR
Base directory for all subdirectories.
Definition: fileio_type.h:109
SLV_5
@ SLV_5
5.0 1429 5.1 1440 5.2 1525 0.3.6
Definition: saveload.h:47
SL_SAVEBYTE
@ SL_SAVEBYTE
Save (but not load) a byte.
Definition: saveload.h:652
SaveFileDone
static void SaveFileDone()
Update the gui accordingly when saving is done and release locks on saveload.
Definition: saveload.cpp:2925
SLF_ALLOW_CONTROL
@ SLF_ALLOW_CONTROL
Allow control codes in the strings.
Definition: saveload.h:631
SlSkipHandler
Handler that is assigned when there is a struct read in the savegame which is not known to the code.
Definition: saveload.cpp:1856
MemoryDumper::WriteByte
void WriteByte(byte b)
Write a single byte into the dumper.
Definition: saveload.cpp:152
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:581
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:2955
IsGoodGRFConfigList
GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
Check if all GRFs in the GRF config from a savegame can be loaded.
Definition: newgrf_config.cpp:513
_sl_version
SaveLoadVersion _sl_version
the major savegame version identifier
Definition: saveload.cpp:66
SlFixPointers
static void SlFixPointers()
Fix all pointers (convert index -> pointer)
Definition: saveload.cpp:2327
SavegameType
SavegameType
Types of save games.
Definition: saveload.h:373
_date
Date _date
Current date in days (day counter)
Definition: date.cpp:28
SAVEGAME_VERSION
const SaveLoadVersion SAVEGAME_VERSION
Current savegame version of OpenTTD.
ZlibSaveFilter
Filter using Zlib compression.
Definition: saveload.cpp:2599
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:1261
NeedLength
NeedLength
Definition: saveload.cpp:80
SlSaveLoadRef
void SlSaveLoadRef(void *ptr, VarType conv)
Handle conversion for references.
Definition: saveload.cpp:1337
CH_TYPE_MASK
@ CH_TYPE_MASK
All ChunkType values have to be within this mask.
Definition: saveload.h:407
span
A trimmed down version of what std::span will be in C++20.
Definition: span_type.hpp:60
NL_CALCLENGTH
@ NL_CALCLENGTH
need to calculate the length
Definition: saveload.cpp:83
SaveFilter::Finish
virtual void Finish()
Prepare everything to finish writing the savegame.
Definition: saveload_filter.h:88
ChunkHandler::Save
virtual void Save() const
Save the chunk.
Definition: saveload.h:424
CH_READONLY
@ CH_READONLY
Chunk is never saved.
Definition: saveload.h:408
SlCalcDequeLen
static size_t SlCalcDequeLen(const void *deque, VarType conv)
Return the size in bytes of a std::deque.
Definition: saveload.cpp:1476
SlWriteByte
void SlWriteByte(byte b)
Wrapper for writing a byte to the dumper.
Definition: saveload.cpp:434
ChunkHandler::id
uint32 id
Unique ID (4 letters).
Definition: saveload.h:413
SL_VAR
@ SL_VAR
Save/load a variable.
Definition: saveload.h:639
StrMakeValidInPlace
void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:273
_savegame_format
std::string _savegame_format
how to compress savegames
Definition: saveload.cpp:68
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:245
LoadCheckData::error_data
char * error_data
Data to pass to SetDParamStr when displaying error.
Definition: fios.h:34
LZMASaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2773
NL_WANTLENGTH
@ NL_WANTLENGTH
writing length and data
Definition: saveload.cpp:82
GetSaveLoadErrorString
const char * GetSaveLoadErrorString()
Get the string representation of the error message.
Definition: saveload.cpp:2944
ZlibLoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2577
SlCopyInternal
static void SlCopyInternal(void *object, size_t length, VarType conv)
Internal function to save/Load a list of SL_VARs.
Definition: saveload.cpp:1103
SaveFilter::Write
virtual void Write(byte *buf, size_t len)=0
Write a given number of bytes into the savegame.
PersistentStorage
Class for pooled persistent storage of data.
Definition: newgrf_storage.h:221
_savegame_type
SavegameType _savegame_type
type of savegame we are loading
Definition: saveload.cpp:62
SlLoadCheckChunks
static void SlLoadCheckChunks()
Load all chunks for savegame checking.
Definition: saveload.cpp:2312
ZlibSaveFilter::ZlibSaveFilter
ZlibSaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2607
CopyFromOldName
std::string CopyFromOldName(StringID id)
Copy and convert old custom names to UTF-8.
Definition: strings_sl.cpp:60
SlVector
static void SlVector(void *vector, VarType conv)
Save/load a std::vector.
Definition: saveload.cpp:1539
FileReader::file
FILE * file
The file to read from.
Definition: saveload.cpp:2342
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:355
SaveLoad::cmd
SaveLoadType cmd
The action to take with the saved/loaded type, All types need different action.
Definition: saveload.h:661
SLV_END_PATCHPACKS
@ SLV_END_PATCHPACKS
286 Last known patchpack to use a version just above ours.
Definition: saveload.h:326
SLRefType
SLRefType
Type of reference (SLE_REF, SLE_CONDREF).
Definition: saveload.h:540
StartNewThread
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:46
SlSaveLoadConv
static void SlSaveLoadConv(void *ptr, VarType conv)
Handle all conversion and typechecking of variables here.
Definition: saveload.cpp:855
ZlibSaveFilter::WriteLoop
void WriteLoop(byte *p, size_t len, int mode)
Helper loop for writing the data.
Definition: saveload.cpp:2625
FileWriter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2401
GamelogStartAction
void GamelogStartAction(GamelogActionType at)
Stores information about new action, but doesn't allocate it Action is allocated only when there is a...
Definition: gamelog.cpp:69
GetSavegameFormat
static const SaveLoadFormat * GetSavegameFormat(const std::string &full_name, byte *compression_level)
Return the savegameformat of the game.
Definition: saveload.cpp:2841
SaveLoadParams::lf
LoadFilter * lf
Filter to read the savegame from.
Definition: saveload.cpp:208
NoCompSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2541
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
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:2966
SaveLoadFormat::name
const char * name
name of the compressor/decompressor (debug-only)
Definition: saveload.cpp:2795
SlCalcRefListLen
static size_t SlCalcRefListLen(const void *list, VarType conv)
Return the size in bytes of a list.
Definition: saveload.cpp:1449
GUISettings::keep_all_autosave
bool keep_all_autosave
name the autosave in a different way
Definition: settings_type.h:139
ChunkHandlers
static const std::vector< ChunkHandlerRef > & ChunkHandlers()
Definition: saveload.cpp:218
SL_ARR
@ SL_ARR
Save/load a fixed-size array of SL_VAR elements.
Definition: saveload.h:646
SLE_FILE_STRINGID
@ SLE_FILE_STRINGID
StringID offset into strings-array.
Definition: saveload.h:575
REF_STORAGE
@ REF_STORAGE
Load/save a reference to a persistent storage.
Definition: saveload.h:550
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
SaveLoadVersion
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
Definition: saveload.h:34
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
SLA_PTRS
@ SLA_PTRS
fixing pointers
Definition: saveload.cpp:75
IsSavegameVersionBefore
static bool IsSavegameVersionBefore(SaveLoadVersion major, byte minor=0)
Checks whether the savegame is below major.
Definition: saveload.h:1030
MemoryDumper::Flush
void Flush(SaveFilter *writer)
Flush this dumper into a writer.
Definition: saveload.cpp:168
SaveFileStart
static void SaveFileStart()
Update the gui accordingly when starting saving and set locks on saveload.
Definition: saveload.cpp:2916
REF_ENGINE_RENEWS
@ REF_ENGINE_RENEWS
Load/save a reference to an engine renewal (autoreplace).
Definition: saveload.h:547
DFT_OLD_GAME_FILE
@ DFT_OLD_GAME_FILE
Old save game or scenario file.
Definition: fileio_type.h:30
vseprintf
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:62
REF_VEHICLE
@ REF_VEHICLE
Load/save a reference to a vehicle.
Definition: saveload.h:542
SL_REF
@ SL_REF
Save/load a reference.
Definition: saveload.h:640
DoAutoOrNetsave
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
Definition: saveload.cpp:3325
REF_CARGO_PACKET
@ REF_CARGO_PACKET
Load/save a reference to a cargo packet.
Definition: saveload.h:548
SL_STRUCT
@ SL_STRUCT
Save/load a struct.
Definition: saveload.h:641
DoSave
static SaveOrLoadResult DoSave(SaveFilter *writer, bool threaded)
Actually perform the saving of the savegame.
Definition: saveload.cpp:3024
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:2685
ReadBuffer::bufp
byte * bufp
Location we're at reading the buffer.
Definition: saveload.cpp:92
SlAutolength
void SlAutolength(AutolengthProc *proc, void *arg)
Do something of which I have no idea what it is :P.
Definition: saveload.cpp:2094
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:545
SaveLoadParams::error_str
StringID error_str
the translatable error message to show
Definition: saveload.cpp:210
ChunkHandler::Load
virtual void Load() const =0
Load the chunk.
ZlibSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2654
BSWAP32
static uint32 BSWAP32(uint32 x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:390
SlSkipHandler::GetDescription
virtual SaveLoadTable GetDescription() const override
Get the description of the fields in the savegame.
Definition: saveload.cpp:1875
SlString
static void SlString(void *ptr, size_t length, VarType conv)
Save/Load a string.
Definition: saveload.cpp:970
GamelogStopAction
void GamelogStopAction()
Stops logging of any changes.
Definition: gamelog.cpp:78
StringValidationSettings
StringValidationSettings
Settings for the string validation.
Definition: string_type.h:49
SlGetStructListLength
size_t SlGetStructListLength(size_t limit)
Get the length of this list; if it exceeds the limit, error out.
Definition: saveload.cpp:1826
SaveLoad::handler
std::shared_ptr< SaveLoadHandler > handler
Custom handler for Save/Load procs.
Definition: saveload.h:669
LoadCheckData::error
StringID error
Error message from loading. INVALID_STRING_ID if no error.
Definition: fios.h:33
GenerateDefaultSaveName
void GenerateDefaultSaveName(char *buf, const char *last)
Fill the buffer with the default name for a savegame or screenshot.
Definition: saveload.cpp:3354
WriteValue
void WriteValue(void *ptr, VarType conv, int64 val)
Write the value of a setting.
Definition: saveload.cpp:829
SL_VECTOR
@ SL_VECTOR
Save/load a vector of SL_VAR elements.
Definition: saveload.h:648
SlCalcVectorLen
static size_t SlCalcVectorLen(const void *vector, VarType conv)
Return the size in bytes of a std::vector.
Definition: saveload.cpp:1518
MemoryDumper::bufe
byte * bufe
End of the buffer we write to.
Definition: saveload.cpp:134
SaveLoadParams::expect_table_header
bool expect_table_header
In the case of a table, if the header is saved/loaded.
Definition: saveload.cpp:202
SL_MAX_VERSION
@ SL_MAX_VERSION
Highest possible saveload version.
Definition: saveload.h:348
SlLoadCheckChunk
static void SlLoadCheckChunk(const ChunkHandler &ch)
Load a chunk of data for checking savegames.
Definition: saveload.cpp:2190
SlError
void NORETURN SlError(StringID string, const char *extra_msg)
Error handler.
Definition: saveload.cpp:333
REF_LINK_GRAPH_JOB
@ REF_LINK_GRAPH_JOB
Load/save a reference to a link graph job.
Definition: saveload.h:552
SlCalcNetStringLen
static size_t SlCalcNetStringLen(const char *ptr, size_t length)
Calculate the net length of a string.
Definition: saveload.cpp:912
ZlibLoadFilter::z
z_stream z
Stream state we are reading from.
Definition: saveload.cpp:2558
LZMALoadFilter::~LZMALoadFilter
~LZMALoadFilter()
Clean everything up.
Definition: saveload.cpp:2699
ReadBuffer::ReadBuffer
ReadBuffer(LoadFilter *reader)
Initialise our variables.
Definition: saveload.cpp:101
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:216
StringID
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
SaveLoadParams::need_length
NeedLength need_length
working in NeedLength (Autolength) mode?
Definition: saveload.cpp:196
SlErrorCorruptFmt
void NORETURN SlErrorCorruptFmt(const char *format,...)
Issue an SlErrorCorrupt with a format string.
Definition: saveload.cpp:377
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
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:386
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:1370
GUISettings::threaded_saves
bool threaded_saves
should we do threaded saves?
Definition: settings_type.h:138
FT_NONE
@ FT_NONE
nothing to do
Definition: fileio_type.h:17
FiosNumberedSaveName
A savegame name automatically numbered.
Definition: fios.h:131
REF_ORDERLIST
@ REF_ORDERLIST
Load/save a reference to an orderlist.
Definition: saveload.h:549
SaveLoadParams
The saveload struct, containing reader-writer functions, buffer, version, etc.
Definition: saveload.cpp:194
LZMALoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2704
SlGetFieldLength
size_t SlGetFieldLength()
Get the length of the current object.
Definition: saveload.cpp:793
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:1171
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:1361
DoLoad
static SaveOrLoadResult DoLoad(LoadFilter *reader, bool load_check)
Actually perform the loading of a "non-old" savegame.
Definition: saveload.cpp:3073
_saveload_formats
static const SaveLoadFormat _saveload_formats[]
The different saveload formats known/understood by OpenTTD.
Definition: saveload.cpp:2805
FileReader::Reset
void Reset() override
Reset this filter to read from the beginning of the file.
Definition: saveload.cpp:2371
SL_REFLIST
@ SL_REFLIST
Save/load a list of SL_REF elements.
Definition: saveload.h:649
SlErrorCorrupt
void NORETURN SlErrorCorrupt(const char *msg)
Error handler for corrupt savegames.
Definition: saveload.cpp:365
SaveFilter
Interface for filtering a savegame till it is written.
Definition: saveload_filter.h:60
SetAsyncSaveFinish
static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
Called by save thread to tell we finished saving.
Definition: saveload.cpp:398
GetVarMemType
static VarType GetVarMemType(VarType type)
Get the NumberType of a setting.
Definition: saveload.h:1069
SaveLoadParams::action
SaveLoadAction action
are we doing a save or a load atm.
Definition: saveload.cpp:195
endof
#define endof(x)
Get the end element of an fixed size array.
Definition: stdafx.h:394
_file_to_saveload
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:63
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition: order_base.h:260
SanitizeFilename
void SanitizeFilename(char *filename)
Sanitizes a filename, i.e.
Definition: fileio.cpp:1089
SaveWithFilter
SaveOrLoadResult SaveWithFilter(SaveFilter *writer, bool threaded)
Save the game using a (writer) filter.
Definition: saveload.cpp:3056
SlGetGammaLength
static uint SlGetGammaLength(size_t i)
Return how many bytes used to encode a gamma value.
Definition: saveload.cpp:552
SlReadByte
byte SlReadByte()
Wrapper for reading a byte from the buffer.
Definition: saveload.cpp:425
ZlibSaveFilter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: saveload.cpp:2659
LZOSaveFilter
Filter using LZO compression.
Definition: saveload.cpp:2474
SaveLoadParams::obj_len
size_t obj_len
the length of the current object we are busy with
Definition: saveload.cpp:200
SlSkipHandler::LoadCheck
void LoadCheck(void *object) const override
Similar to load, but used only to validate savegames.
Definition: saveload.cpp:1870
LZMASaveFilter::~LZMASaveFilter
~LZMASaveFilter()
Clean up what we allocated.
Definition: saveload.cpp:2741
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:554
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
SlWriteSimpleGamma
static void SlWriteSimpleGamma(size_t i)
Write the header descriptor of an object or an array.
Definition: saveload.cpp:527
SaveLoad::version_from
SaveLoadVersion version_from
Save/load the variable starting from this savegame version.
Definition: saveload.h:664
LoadCheckData::grf_compatibility
GRFListCompatibility grf_compatibility
Summary state of NewGrfs, whether missing files or only compatible found.
Definition: fios.h:44
SaveOrLoadResult
SaveOrLoadResult
Save or load result codes.
Definition: saveload.h:352
GamelogReset
void GamelogReset()
Resets and frees all memory allocated - used before loading or starting a new game.
Definition: gamelog.cpp:115
WL_ERROR
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition: error.h:24
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:596
SaveLoadParams::saveinprogress
bool saveinprogress
Whether there is currently a save in progress.
Definition: saveload.cpp:213
SaveFilter::chain
SaveFilter * chain
Chained to the (savegame) filters.
Definition: saveload_filter.h:62
stredup
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:138
SlSkipHandler::Save
void Save(void *object) const override
Save the object to disk.
Definition: saveload.cpp:1857
SlRefList
static void SlRefList(void *list, VarType conv)
Save/Load a list.
Definition: saveload.cpp:1459
ReadBuffer::read
size_t read
The amount of read bytes so far from the filter.
Definition: saveload.cpp:95
_grfconfig
GRFConfig * _grfconfig
First item in list of current GRF set up.
Definition: newgrf_config.cpp:171
REF_LINK_GRAPH
@ REF_LINK_GRAPH
Load/save a reference to a link graph.
Definition: saveload.h:551
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:76
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
SlStdString
static void SlStdString(void *ptr, VarType conv)
Save/Load a std::string.
Definition: saveload.cpp:1049
SaveLoadFormat::tag
uint32 tag
the 4-letter tag by which it is identified in the savegame
Definition: saveload.cpp:2796
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:386
SaveLoadParams::error
bool error
did an error occur or not
Definition: saveload.cpp:198
CargoPacket
Container for cargo from the same location and time.
Definition: cargopacket.h:43
SL_DEQUE
@ SL_DEQUE
Save/load a deque of SL_VAR elements.
Definition: saveload.h:647
SaveLoadParams::dumper
MemoryDumper * dumper
Memory dumper to write the savegame to.
Definition: saveload.cpp:204
FileReader::~FileReader
~FileReader()
Make sure everything is cleaned up.
Definition: saveload.cpp:2354
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:335
GetVariableAddress
static void * GetVariableAddress(const void *object, const SaveLoad &sld)
Get the address of the variable.
Definition: saveload.h:1100
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:2030
SlCopyBytes
static void SlCopyBytes(void *ptr, size_t length)
Save/Load bytes.
Definition: saveload.cpp:776
LZOLoadFilter
Filter using LZO compression.
Definition: saveload.cpp:2427
MEMORY_CHUNK_SIZE
static const size_t MEMORY_CHUNK_SIZE
Save in chunks of 128 KiB.
Definition: saveload.cpp:87
ProcessAsyncSaveFinish
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition: saveload.cpp:409
MemoryDumper::blocks
std::vector< byte * > blocks
Buffer with blocks of allocated memory.
Definition: saveload.cpp:132
SaveLoadParams::extra_msg
char * extra_msg
the error message
Definition: saveload.cpp:211
FileReader
Yes, simply reading from a file.
Definition: saveload.cpp:2341
SlFindChunkHandler
static const ChunkHandler * SlFindChunkHandler(uint32 id)
Find the ChunkHandler that will be used for processing the found chunk in the savegame or in memory.
Definition: saveload.cpp:2290
_ttdp_version
uint32 _ttdp_version
version of TTDP savegame (if applicable)
Definition: saveload.cpp:65
ReadValue
int64 ReadValue(const void *ptr, VarType conv)
Return a signed-long version of the value of a setting.
Definition: saveload.cpp:805
SaveLoadParams::last_array_index
int last_array_index
in the case of an array, the current and last positions
Definition: saveload.cpp:201
SlCalcRefLen
static size_t SlCalcRefLen()
Return the size in bytes of a reference (pointer)
Definition: saveload.cpp:654
LZMASaveFilter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: saveload.cpp:2778
_async_save_finish
static std::atomic< AsyncSaveFinishProc > _async_save_finish
Callback to call when the savegame loading is finished.
Definition: saveload.cpp:391
SL_ERROR
@ SL_ERROR
error that was caught before internal structures were modified
Definition: saveload.h:354
FileToSaveLoad::detail_ftype
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
Definition: saveload.h:361
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:326
WC_STATUS_BAR
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
Definition: window_type.h:57
ReadBuffer::GetSize
size_t GetSize() const
Get the size of the memory dump made so far.
Definition: saveload.cpp:123
RoadStop
A Stop for a Road Vehicle.
Definition: roadstop_base.h:22
FiosNumberedSaveName::Extension
std::string Extension()
Generate an extension for a savegame name.
Definition: fios.cpp:801
SaveLoad::name
std::string name
Name of this field (optional, used for tables).
Definition: saveload.h:660
SlObject
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
Definition: saveload.cpp:1839
ZlibSaveFilter::~ZlibSaveFilter
~ZlibSaveFilter()
Clean up what we allocated.
Definition: saveload.cpp:2614
ChunkHandler::LoadCheck
virtual void LoadCheck(size_t len=0) const
Load the chunk for game preview.
Definition: saveload.cpp:2117
LZMASaveFilter
Filter using LZMA compression.
Definition: saveload.cpp:2727
SLV_START_PATCHPACKS
@ SLV_START_PATCHPACKS
220 First known patchpack to use a version just above ours.
Definition: saveload.h:325
SlTableHeader
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
Definition: saveload.cpp:1892
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:113
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
SlSetStructListLength
void SlSetStructListLength(size_t length)
Set the length of this list.
Definition: saveload.cpp:1810
SlCalcStringLen
static size_t SlCalcStringLen(const void *ptr, size_t length, VarType conv)
Calculate the gross length of the string that it will occupy in the savegame.
Definition: saveload.cpp:927
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:41
strecat
char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: string.cpp:85
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:3387
SlSkipHandler::GetCompatDescription
virtual SaveLoadCompatTable GetCompatDescription() const override
Get the pre-header description of the fields in the savegame.
Definition: saveload.cpp:1880
SaveLoad
SaveLoad type struct.
Definition: saveload.h:659
Company
Definition: company_base.h:117
LZOSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2485
ClearSaveLoadState
static void ClearSaveLoadState()
Clear/free saveload state.
Definition: saveload.cpp:2900
LoadFilter::chain
LoadFilter * chain
Chained to the (savegame) filters.
Definition: saveload_filter.h:16
LoadFilter::LoadFilter
LoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload_filter.h:22
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
SL_OK
@ SL_OK
completed successfully
Definition: saveload.h:353
SVS_REPLACE_WITH_QUESTION_MARK
@ SVS_REPLACE_WITH_QUESTION_MARK
Replace the unknown/bad bits with question marks.
Definition: string_type.h:51
FiosNumberedSaveName::Filename
std::string Filename()
Generate a savegame name and number according to _settings_client.gui.max_num_autosaves.
Definition: fios.cpp:791
SL_STDSTR
@ SL_STDSTR
Save/load a std::string.
Definition: saveload.h:644
Order
Definition: order_base.h:36
SlSkipBytes
static 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:1147
_lzma_init
static const lzma_stream _lzma_init
Have a copy of an initialised LZMA stream.
Definition: saveload.cpp:2681
SLE_VAR_NAME
@ SLE_VAR_NAME
old custom name to be converted to a char pointer
Definition: saveload.h:597
FileWriter::~FileWriter
~FileWriter()
Make sure everything is cleaned up.
Definition: saveload.cpp:2393
SlCalcObjLength
size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt)
Calculate the size of an object.
Definition: saveload.cpp:1595
SlIterateArray
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition: saveload.cpp:671
SetDParamStr
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:297
FileReader::FileReader
FileReader(FILE *file)
Create the file reader, so it reads from a specific file.
Definition: saveload.cpp:2349
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:2238
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:604
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:25
FileWriter::Finish
void Finish() override
Prepare everything to finish writing the savegame.
Definition: saveload.cpp:2409
FileToSaveLoad::file_op
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:360
FileWriter
Yes, simply writing to a file.
Definition: saveload.cpp:2381
ReadBuffer::bufe
byte * bufe
End of the buffer we can read from.
Definition: saveload.cpp:93
MemoryDumper
Container for dumping the savegame (quickly) to memory.
Definition: saveload.cpp:131
SL_STRUCTLIST
@ SL_STRUCTLIST
Save/load a list of structs.
Definition: saveload.h:650
AllocaM
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:132