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

OpenTTD Source 14.0-beta3

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