OpenTTD Source  14.0-beta1
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 
58 
61 
62 uint32_t _ttdp_version;
65 std::string _savegame_format;
67 
75 };
76 
77 enum NeedLength {
78  NL_NONE = 0,
81 };
82 
84 static const size_t MEMORY_CHUNK_SIZE = 128 * 1024;
85 
87 struct ReadBuffer {
89  byte *bufp;
90  byte *bufe;
92  size_t read;
93 
98  ReadBuffer(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(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 
194  byte block_mode;
195  bool error;
196 
197  size_t obj_len;
198  int array_index, last_array_index;
200 
203 
206 
208  std::string extra_msg;
209 
211 };
212 
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. */
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. */
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 
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 
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 
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 {
638  _sl.array_index = index;
639 }
640 
641 static size_t _next_offs;
642 
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 
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:
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 
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 
945  if ((conv & SLF_ALLOW_CONTROL) != 0) {
948  }
949  if ((conv & SLF_ALLOW_NEWLINE) != 0) {
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: {
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>>
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 {
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 
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 
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: {
1592  }
1593  sld.handler->LoadCheck(object);
1594  break;
1595  }
1596 
1597  case SLA_LOAD: {
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 
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 
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) {
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;
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 */
1913  _sl.obj_len = 0;
1914  proc(arg);
1915 
1916  /* Setup length */
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 
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;
2078  ch.Save();
2079  SlWriteArrayLength(0); // Terminate arrays
2080  break;
2081  case CH_SPARSE_TABLE:
2082  case CH_SPARSE_ARRAY:
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 
2162  FILE *file;
2163  long begin;
2164 
2169  FileReader(FILE *file) : LoadFilter(nullptr), file(file), begin(ftell(file))
2170  {
2171  }
2172 
2175  {
2176  if (this->file != nullptr) fclose(this->file);
2177  this->file = nullptr;
2178 
2179  /* Make sure we don't double free. */
2180  _sl.sf = nullptr;
2181  }
2182 
2183  size_t Read(byte *buf, size_t size) override
2184  {
2185  /* We're in the process of shutting down, i.e. in "failure" mode. */
2186  if (this->file == nullptr) return 0;
2187 
2188  return fread(buf, 1, size, this->file);
2189  }
2190 
2191  void Reset() override
2192  {
2193  clearerr(this->file);
2194  if (fseek(this->file, this->begin, SEEK_SET)) {
2195  Debug(sl, 1, "Could not reset the file reading");
2196  }
2197  }
2198 };
2199 
2202  FILE *file;
2203 
2208  FileWriter(FILE *file) : SaveFilter(nullptr), file(file)
2209  {
2210  }
2211 
2214  {
2215  this->Finish();
2216 
2217  /* Make sure we don't double free. */
2218  _sl.sf = nullptr;
2219  }
2220 
2221  void Write(byte *buf, size_t size) override
2222  {
2223  /* We're in the process of shutting down, i.e. in "failure" mode. */
2224  if (this->file == nullptr) return;
2225 
2226  if (fwrite(buf, 1, size, this->file) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
2227  }
2228 
2229  void Finish() override
2230  {
2231  if (this->file != nullptr) fclose(this->file);
2232  this->file = nullptr;
2233  }
2234 };
2235 
2236 /*******************************************
2237  ********** START OF LZO CODE **************
2238  *******************************************/
2239 
2240 #ifdef WITH_LZO
2241 #include <lzo/lzo1x.h>
2242 
2244 static const uint LZO_BUFFER_SIZE = 8192;
2245 
2253  {
2254  if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2255  }
2256 
2257  size_t Read(byte *buf, size_t ssize) override
2258  {
2259  assert(ssize >= LZO_BUFFER_SIZE);
2260 
2261  /* Buffer size is from the LZO docs plus the chunk header size. */
2262  byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32_t) * 2];
2263  uint32_t tmp[2];
2264  uint32_t size;
2265  lzo_uint len = ssize;
2266 
2267  /* Read header*/
2268  if (this->chain->Read((byte*)tmp, sizeof(tmp)) != sizeof(tmp)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE, "File read failed");
2269 
2270  /* Check if size is bad */
2271  ((uint32_t*)out)[0] = size = tmp[1];
2272 
2273  if (_sl_version != SL_MIN_VERSION) {
2274  tmp[0] = TO_BE32(tmp[0]);
2275  size = TO_BE32(size);
2276  }
2277 
2278  if (size >= sizeof(out)) SlErrorCorrupt("Inconsistent size");
2279 
2280  /* Read block */
2281  if (this->chain->Read(out + sizeof(uint32_t), size) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2282 
2283  /* Verify checksum */
2284  if (tmp[0] != lzo_adler32(0, out, size + sizeof(uint32_t))) SlErrorCorrupt("Bad checksum");
2285 
2286  /* Decompress */
2287  int ret = lzo1x_decompress_safe(out + sizeof(uint32_t) * 1, size, buf, &len, nullptr);
2288  if (ret != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2289  return len;
2290  }
2291 };
2292 
2300  {
2301  if (lzo_init() != LZO_E_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2302  }
2303 
2304  void Write(byte *buf, size_t size) override
2305  {
2306  const lzo_bytep in = buf;
2307  /* Buffer size is from the LZO docs plus the chunk header size. */
2308  byte out[LZO_BUFFER_SIZE + LZO_BUFFER_SIZE / 16 + 64 + 3 + sizeof(uint32_t) * 2];
2309  byte wrkmem[LZO1X_1_MEM_COMPRESS];
2310  lzo_uint outlen;
2311 
2312  do {
2313  /* Compress up to LZO_BUFFER_SIZE bytes at once. */
2314  lzo_uint len = size > LZO_BUFFER_SIZE ? LZO_BUFFER_SIZE : (lzo_uint)size;
2315  lzo1x_1_compress(in, len, out + sizeof(uint32_t) * 2, &outlen, wrkmem);
2316  ((uint32_t*)out)[1] = TO_BE32((uint32_t)outlen);
2317  ((uint32_t*)out)[0] = TO_BE32(lzo_adler32(0, out + sizeof(uint32_t), outlen + sizeof(uint32_t)));
2318  this->chain->Write(out, outlen + sizeof(uint32_t) * 2);
2319 
2320  /* Move to next data chunk. */
2321  size -= len;
2322  in += len;
2323  } while (size > 0);
2324  }
2325 };
2326 
2327 #endif /* WITH_LZO */
2328 
2329 /*********************************************
2330  ******** START OF NOCOMP CODE (uncompressed)*
2331  *********************************************/
2332 
2340  {
2341  }
2342 
2343  size_t Read(byte *buf, size_t size) override
2344  {
2345  return this->chain->Read(buf, size);
2346  }
2347 };
2348 
2356  {
2357  }
2358 
2359  void Write(byte *buf, size_t size) override
2360  {
2361  this->chain->Write(buf, size);
2362  }
2363 };
2364 
2365 /********************************************
2366  ********** START OF ZLIB CODE **************
2367  ********************************************/
2368 
2369 #if defined(WITH_ZLIB)
2370 #include <zlib.h>
2371 
2374  z_stream z;
2382  {
2383  memset(&this->z, 0, sizeof(this->z));
2384  if (inflateInit(&this->z) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2385  }
2386 
2388  ~ZlibLoadFilter()
2389  {
2390  inflateEnd(&this->z);
2391  }
2392 
2393  size_t Read(byte *buf, size_t size) override
2394  {
2395  this->z.next_out = buf;
2396  this->z.avail_out = (uint)size;
2397 
2398  do {
2399  /* read more bytes from the file? */
2400  if (this->z.avail_in == 0) {
2401  this->z.next_in = this->fread_buf;
2402  this->z.avail_in = (uint)this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2403  }
2404 
2405  /* inflate the data */
2406  int r = inflate(&this->z, 0);
2407  if (r == Z_STREAM_END) break;
2408 
2409  if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "inflate() failed");
2410  } while (this->z.avail_out != 0);
2411 
2412  return size - this->z.avail_out;
2413  }
2414 };
2415 
2418  z_stream z;
2420 
2426  ZlibSaveFilter(SaveFilter *chain, byte compression_level) : SaveFilter(chain)
2427  {
2428  memset(&this->z, 0, sizeof(this->z));
2429  if (deflateInit(&this->z, compression_level) != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2430  }
2431 
2434  {
2435  deflateEnd(&this->z);
2436  }
2437 
2444  void WriteLoop(byte *p, size_t len, int mode)
2445  {
2446  uint n;
2447  this->z.next_in = p;
2448  this->z.avail_in = (uInt)len;
2449  do {
2450  this->z.next_out = this->fwrite_buf;
2451  this->z.avail_out = sizeof(this->fwrite_buf);
2452 
2460  int r = deflate(&this->z, mode);
2461 
2462  /* bytes were emitted? */
2463  if ((n = sizeof(this->fwrite_buf) - this->z.avail_out) != 0) {
2464  this->chain->Write(this->fwrite_buf, n);
2465  }
2466  if (r == Z_STREAM_END) break;
2467 
2468  if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "zlib returned error code");
2469  } while (this->z.avail_in || !this->z.avail_out);
2470  }
2471 
2472  void Write(byte *buf, size_t size) override
2473  {
2474  this->WriteLoop(buf, size, 0);
2475  }
2476 
2477  void Finish() override
2478  {
2479  this->WriteLoop(nullptr, 0, Z_FINISH);
2480  this->chain->Finish();
2481  }
2482 };
2483 
2484 #endif /* WITH_ZLIB */
2485 
2486 /********************************************
2487  ********** START OF LZMA CODE **************
2488  ********************************************/
2489 
2490 #if defined(WITH_LIBLZMA)
2491 #include <lzma.h>
2492 
2499 static const lzma_stream _lzma_init = LZMA_STREAM_INIT;
2500 
2503  lzma_stream lzma;
2505 
2511  {
2512  /* Allow saves up to 256 MB uncompressed */
2513  if (lzma_auto_decoder(&this->lzma, 1 << 28, 0) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize decompressor");
2514  }
2515 
2518  {
2519  lzma_end(&this->lzma);
2520  }
2521 
2522  size_t Read(byte *buf, size_t size) override
2523  {
2524  this->lzma.next_out = buf;
2525  this->lzma.avail_out = size;
2526 
2527  do {
2528  /* read more bytes from the file? */
2529  if (this->lzma.avail_in == 0) {
2530  this->lzma.next_in = this->fread_buf;
2531  this->lzma.avail_in = this->chain->Read(this->fread_buf, sizeof(this->fread_buf));
2532  }
2533 
2534  /* inflate the data */
2535  lzma_ret r = lzma_code(&this->lzma, LZMA_RUN);
2536  if (r == LZMA_STREAM_END) break;
2537  if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2538  } while (this->lzma.avail_out != 0);
2539 
2540  return size - this->lzma.avail_out;
2541  }
2542 };
2543 
2546  lzma_stream lzma;
2548 
2555  {
2556  if (lzma_easy_encoder(&this->lzma, compression_level, LZMA_CHECK_CRC32) != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
2557  }
2558 
2561  {
2562  lzma_end(&this->lzma);
2563  }
2564 
2571  void WriteLoop(byte *p, size_t len, lzma_action action)
2572  {
2573  size_t n;
2574  this->lzma.next_in = p;
2575  this->lzma.avail_in = len;
2576  do {
2577  this->lzma.next_out = this->fwrite_buf;
2578  this->lzma.avail_out = sizeof(this->fwrite_buf);
2579 
2580  lzma_ret r = lzma_code(&this->lzma, action);
2581 
2582  /* bytes were emitted? */
2583  if ((n = sizeof(this->fwrite_buf) - this->lzma.avail_out) != 0) {
2584  this->chain->Write(this->fwrite_buf, n);
2585  }
2586  if (r == LZMA_STREAM_END) break;
2587  if (r != LZMA_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "liblzma returned error code");
2588  } while (this->lzma.avail_in || !this->lzma.avail_out);
2589  }
2590 
2591  void Write(byte *buf, size_t size) override
2592  {
2593  this->WriteLoop(buf, size, LZMA_RUN);
2594  }
2595 
2596  void Finish() override
2597  {
2598  this->WriteLoop(nullptr, 0, LZMA_FINISH);
2599  this->chain->Finish();
2600  }
2601 };
2602 
2603 #endif /* WITH_LIBLZMA */
2604 
2605 /*******************************************
2606  ************* END OF CODE *****************
2607  *******************************************/
2608 
2611  const char *name;
2612  uint32_t tag;
2614  LoadFilter *(*init_load)(LoadFilter *chain);
2615  SaveFilter *(*init_write)(SaveFilter *chain, byte compression);
2618  byte default_compression;
2620 };
2624 #if defined(WITH_LZO)
2625  /* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
2626  {"lzo", TO_BE32X('OTTD'), CreateLoadFilter<LZOLoadFilter>, CreateSaveFilter<LZOSaveFilter>, 0, 0, 0},
2627 #else
2628  {"lzo", TO_BE32X('OTTD'), nullptr, nullptr, 0, 0, 0},
2629 #endif
2630  /* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
2631  {"none", TO_BE32X('OTTN'), CreateLoadFilter<NoCompLoadFilter>, CreateSaveFilter<NoCompSaveFilter>, 0, 0, 0},
2632 #if defined(WITH_ZLIB)
2633  /* After level 6 the speed reduction is significant (1.5x to 2.5x slower per level), but the reduction in filesize is
2634  * fairly insignificant (~1% for each step). Lower levels become ~5-10% bigger by each level than level 6 while level
2635  * 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
2636  {"zlib", TO_BE32X('OTTZ'), CreateLoadFilter<ZlibLoadFilter>, CreateSaveFilter<ZlibSaveFilter>, 0, 6, 9},
2637 #else
2638  {"zlib", TO_BE32X('OTTZ'), nullptr, nullptr, 0, 0, 0},
2639 #endif
2640 #if defined(WITH_LIBLZMA)
2641  /* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
2642  * Higher compression levels are possible, and might improve savegame size by up to 25%, but are also up to 10 times slower.
2643  * The next significant reduction in file size is at level 4, but that is already 4 times slower. Level 3 is primarily 50%
2644  * slower while not improving the filesize, while level 0 and 1 are faster, but don't reduce savegame size much.
2645  * It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
2646  {"lzma", TO_BE32X('OTTX'), CreateLoadFilter<LZMALoadFilter>, CreateSaveFilter<LZMASaveFilter>, 0, 2, 9},
2647 #else
2648  {"lzma", TO_BE32X('OTTX'), nullptr, nullptr, 0, 0, 0},
2649 #endif
2650 };
2651 
2659 static const SaveLoadFormat *GetSavegameFormat(const std::string &full_name, byte *compression_level)
2660 {
2661  const SaveLoadFormat *def = lastof(_saveload_formats);
2662 
2663  /* find default savegame format, the highest one with which files can be written */
2664  while (!def->init_write) def--;
2665 
2666  if (!full_name.empty()) {
2667  /* Get the ":..." of the compression level out of the way */
2668  size_t separator = full_name.find(':');
2669  bool has_comp_level = separator != std::string::npos;
2670  const std::string name(full_name, 0, has_comp_level ? separator : full_name.size());
2671 
2672  for (const SaveLoadFormat *slf = &_saveload_formats[0]; slf != endof(_saveload_formats); slf++) {
2673  if (slf->init_write != nullptr && name.compare(slf->name) == 0) {
2674  *compression_level = slf->default_compression;
2675  if (has_comp_level) {
2676  const std::string complevel(full_name, separator + 1);
2677 
2678  /* Get the level and determine whether all went fine. */
2679  size_t processed;
2680  long level = std::stol(complevel, &processed, 10);
2681  if (processed == 0 || level != Clamp(level, slf->min_compression, slf->max_compression)) {
2682  SetDParamStr(0, complevel);
2683  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_LEVEL, WL_CRITICAL);
2684  } else {
2685  *compression_level = level;
2686  }
2687  }
2688  return slf;
2689  }
2690  }
2691 
2692  SetDParamStr(0, name);
2693  SetDParamStr(1, def->name);
2694  ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM, WL_CRITICAL);
2695  }
2696  *compression_level = def->default_compression;
2697  return def;
2698 }
2699 
2700 /* actual loader/saver function */
2701 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
2702 extern bool AfterLoadGame();
2703 extern bool LoadOldSaveGame(const std::string &file);
2704 
2708 static void ResetSaveloadData()
2709 {
2710  ResetTempEngineData();
2711  ResetLabelMaps();
2712  ResetOldWaypoints();
2713 }
2714 
2718 static inline void ClearSaveLoadState()
2719 {
2720  delete _sl.dumper;
2721  _sl.dumper = nullptr;
2722 
2723  delete _sl.sf;
2724  _sl.sf = nullptr;
2725 
2726  delete _sl.reader;
2727  _sl.reader = nullptr;
2728 
2729  delete _sl.lf;
2730  _sl.lf = nullptr;
2731 }
2732 
2734 static void SaveFileStart()
2735 {
2736  SetMouseCursorBusy(true);
2737 
2739  _sl.saveinprogress = true;
2740 }
2741 
2743 static void SaveFileDone()
2744 {
2745  SetMouseCursorBusy(false);
2746 
2748  _sl.saveinprogress = false;
2749 
2750 #ifdef __EMSCRIPTEN__
2751  EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
2752 #endif
2753 }
2754 
2757 {
2758  _sl.error_str = str;
2759 }
2760 
2763 {
2764  SetDParam(0, _sl.error_str);
2766 
2767  static std::string err_str;
2768  err_str = GetString(_sl.action == SLA_SAVE ? STR_ERROR_GAME_SAVE_FAILED : STR_ERROR_GAME_LOAD_FAILED);
2769  return err_str.c_str();
2770 }
2771 
2773 static void SaveFileError()
2774 {
2776  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
2777  SaveFileDone();
2778 }
2779 
2784 static SaveOrLoadResult SaveFileToDisk(bool threaded)
2785 {
2786  try {
2787  byte compression;
2788  const SaveLoadFormat *fmt = GetSavegameFormat(_savegame_format, &compression);
2789 
2790  /* We have written our stuff to memory, now write it to file! */
2791  uint32_t hdr[2] = { fmt->tag, TO_BE32(SAVEGAME_VERSION << 16) };
2792  _sl.sf->Write((byte*)hdr, sizeof(hdr));
2793 
2794  _sl.sf = fmt->init_write(_sl.sf, compression);
2795  _sl.dumper->Flush(_sl.sf);
2796 
2798 
2799  if (threaded) SetAsyncSaveFinish(SaveFileDone);
2800 
2801  return SL_OK;
2802  } catch (...) {
2804 
2806 
2807  /* We don't want to shout when saving is just
2808  * cancelled due to a client disconnecting. */
2809  if (_sl.error_str != STR_NETWORK_ERROR_LOSTCONNECTION) {
2810  /* Skip the "colour" character */
2811  Debug(sl, 0, "{}", GetSaveLoadErrorString() + 3);
2812  asfp = SaveFileError;
2813  }
2814 
2815  if (threaded) {
2816  SetAsyncSaveFinish(asfp);
2817  } else {
2818  asfp();
2819  }
2820  return SL_ERROR;
2821  }
2822 }
2823 
2824 void WaitTillSaved()
2825 {
2826  if (!_save_thread.joinable()) return;
2827 
2828  _save_thread.join();
2829 
2830  /* Make sure every other state is handled properly as well. */
2832 }
2833 
2842 static SaveOrLoadResult DoSave(SaveFilter *writer, bool threaded)
2843 {
2844  assert(!_sl.saveinprogress);
2845 
2846  _sl.dumper = new MemoryDumper();
2847  _sl.sf = writer;
2848 
2850 
2851  SaveViewportBeforeSaveGame();
2852  SlSaveChunks();
2853 
2854  SaveFileStart();
2855 
2856  if (!threaded || !StartNewThread(&_save_thread, "ottd:savegame", &SaveFileToDisk, true)) {
2857  if (threaded) Debug(sl, 1, "Cannot create savegame thread, reverting to single-threaded mode...");
2858 
2859  SaveOrLoadResult result = SaveFileToDisk(false);
2860  SaveFileDone();
2861 
2862  return result;
2863  }
2864 
2865  return SL_OK;
2866 }
2867 
2875 {
2876  try {
2877  _sl.action = SLA_SAVE;
2878  return DoSave(writer, threaded);
2879  } catch (...) {
2881  return SL_ERROR;
2882  }
2883 }
2884 
2891 static SaveOrLoadResult DoLoad(LoadFilter *reader, bool load_check)
2892 {
2893  _sl.lf = reader;
2894 
2895  if (load_check) {
2896  /* Clear previous check data */
2898  /* Mark SL_LOAD_CHECK as supported for this savegame. */
2899  _load_check_data.checkable = true;
2900  }
2901 
2902  uint32_t hdr[2];
2903  if (_sl.lf->Read((byte*)hdr, sizeof(hdr)) != sizeof(hdr)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
2904 
2905  /* see if we have any loader for this type. */
2906  const SaveLoadFormat *fmt = _saveload_formats;
2907  for (;;) {
2908  /* No loader found, treat as version 0 and use LZO format */
2909  if (fmt == endof(_saveload_formats)) {
2910  Debug(sl, 0, "Unknown savegame type, trying to load it as the buggy format");
2911  _sl.lf->Reset();
2913  _sl_minor_version = 0;
2914 
2915  /* Try to find the LZO savegame format; it uses 'OTTD' as tag. */
2916  fmt = _saveload_formats;
2917  for (;;) {
2918  if (fmt == endof(_saveload_formats)) {
2919  /* Who removed LZO support? */
2920  NOT_REACHED();
2921  }
2922  if (fmt->tag == TO_BE32X('OTTD')) break;
2923  fmt++;
2924  }
2925  break;
2926  }
2927 
2928  if (fmt->tag == hdr[0]) {
2929  /* check version number */
2930  _sl_version = (SaveLoadVersion)(TO_BE32(hdr[1]) >> 16);
2931  /* Minor is not used anymore from version 18.0, but it is still needed
2932  * in versions before that (4 cases) which can't be removed easy.
2933  * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */
2934  _sl_minor_version = (TO_BE32(hdr[1]) >> 8) & 0xFF;
2935 
2936  Debug(sl, 1, "Loading savegame version {}", _sl_version);
2937 
2938  /* Is the version higher than the current? */
2939  if (_sl_version > SAVEGAME_VERSION) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME);
2940  if (_sl_version >= SLV_START_PATCHPACKS && _sl_version <= SLV_END_PATCHPACKS) SlError(STR_GAME_SAVELOAD_ERROR_PATCHPACK);
2941  break;
2942  }
2943 
2944  fmt++;
2945  }
2946 
2947  /* loader for this savegame type is not implemented? */
2948  if (fmt->init_load == nullptr) {
2949  SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, fmt::format("Loader for '{}' is not available.", fmt->name));
2950  }
2951 
2952  _sl.lf = fmt->init_load(_sl.lf);
2953  _sl.reader = new ReadBuffer(_sl.lf);
2954  _next_offs = 0;
2955 
2956  if (!load_check) {
2958 
2959  /* Old maps were hardcoded to 256x256 and thus did not contain
2960  * any mapsize information. Pre-initialize to 256x256 to not to
2961  * confuse old games */
2962  InitializeGame(256, 256, true, true);
2963 
2964  _gamelog.Reset();
2965 
2967  /*
2968  * NewGRFs were introduced between 0.3,4 and 0.3.5, which both
2969  * shared savegame version 4. Anything before that 'obviously'
2970  * does not have any NewGRFs. Between the introduction and
2971  * savegame version 41 (just before 0.5) the NewGRF settings
2972  * were not stored in the savegame and they were loaded by
2973  * using the settings from the main menu.
2974  * So, to recap:
2975  * - savegame version < 4: do not load any NewGRFs.
2976  * - savegame version >= 41: load NewGRFs from savegame, which is
2977  * already done at this stage by
2978  * overwriting the main menu settings.
2979  * - other savegame versions: use main menu settings.
2980  *
2981  * This means that users *can* crash savegame version 4..40
2982  * savegames if they set incompatible NewGRFs in the main menu,
2983  * but can't crash anymore for savegame version < 4 savegames.
2984  *
2985  * Note: this is done here because AfterLoadGame is also called
2986  * for TTO/TTD/TTDP savegames which have their own NewGRF logic.
2987  */
2989  }
2990  }
2991 
2992  if (load_check) {
2993  /* Load chunks into _load_check_data.
2994  * No pools are loaded. References are not possible, and thus do not need resolving. */
2996  } else {
2997  /* Load chunks and resolve references */
2998  SlLoadChunks();
2999  SlFixPointers();
3000  }
3001 
3003 
3005 
3006  if (load_check) {
3007  /* The only part from AfterLoadGame() we need */
3009  } else {
3011 
3012  /* After loading fix up savegame for any internal changes that
3013  * might have occurred since then. If it fails, load back the old game. */
3014  if (!AfterLoadGame()) {
3015  _gamelog.StopAction();
3016  return SL_REINIT;
3017  }
3018 
3019  _gamelog.StopAction();
3020  }
3021 
3022  return SL_OK;
3023 }
3024 
3031 {
3032  try {
3033  _sl.action = SLA_LOAD;
3034  return DoLoad(reader, false);
3035  } catch (...) {
3037  return SL_REINIT;
3038  }
3039 }
3040 
3050 SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
3051 {
3052  /* An instance of saving is already active, so don't go saving again */
3053  if (_sl.saveinprogress && fop == SLO_SAVE && dft == DFT_GAME_FILE && threaded) {
3054  /* if not an autosave, but a user action, show error message */
3055  if (!_do_autosave) ShowErrorMessage(STR_ERROR_SAVE_STILL_IN_PROGRESS, INVALID_STRING_ID, WL_ERROR);
3056  return SL_OK;
3057  }
3058  WaitTillSaved();
3059 
3060  try {
3061  /* Load a TTDLX or TTDPatch game */
3062  if (fop == SLO_LOAD && dft == DFT_OLD_GAME_FILE) {
3064 
3065  InitializeGame(256, 256, true, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
3066 
3067  /* TTD/TTO savegames have no NewGRFs, TTDP savegame have them
3068  * and if so a new NewGRF list will be made in LoadOldSaveGame.
3069  * Note: this is done here because AfterLoadGame is also called
3070  * for OTTD savegames which have their own NewGRF logic. */
3072  _gamelog.Reset();
3073  if (!LoadOldSaveGame(filename)) return SL_REINIT;
3075  _sl_minor_version = 0;
3077  if (!AfterLoadGame()) {
3078  _gamelog.StopAction();
3079  return SL_REINIT;
3080  }
3081  _gamelog.StopAction();
3082  return SL_OK;
3083  }
3084 
3085  assert(dft == DFT_GAME_FILE);
3086  switch (fop) {
3087  case SLO_CHECK:
3089  break;
3090 
3091  case SLO_LOAD:
3092  _sl.action = SLA_LOAD;
3093  break;
3094 
3095  case SLO_SAVE:
3096  _sl.action = SLA_SAVE;
3097  break;
3098 
3099  default: NOT_REACHED();
3100  }
3101 
3102  FILE *fh = (fop == SLO_SAVE) ? FioFOpenFile(filename, "wb", sb) : FioFOpenFile(filename, "rb", sb);
3103 
3104  /* Make it a little easier to load savegames from the console */
3105  if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SAVE_DIR);
3106  if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", BASE_DIR);
3107  if (fh == nullptr && fop != SLO_SAVE) fh = FioFOpenFile(filename, "rb", SCENARIO_DIR);
3108 
3109  if (fh == nullptr) {
3110  SlError(fop == SLO_SAVE ? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE : STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
3111  }
3112 
3113  if (fop == SLO_SAVE) { // SAVE game
3114  Debug(desync, 1, "save: {:08x}; {:02x}; {}", TimerGameEconomy::date, TimerGameEconomy::date_fract, filename);
3115  if (!_settings_client.gui.threaded_saves) threaded = false;
3116 
3117  return DoSave(new FileWriter(fh), threaded);
3118  }
3119 
3120  /* LOAD game */
3121  assert(fop == SLO_LOAD || fop == SLO_CHECK);
3122  Debug(desync, 1, "load: {}", filename);
3123  return DoLoad(new FileReader(fh), fop == SLO_CHECK);
3124  } catch (...) {
3125  /* This code may be executed both for old and new save games. */
3127 
3128  /* Skip the "colour" character */
3129  if (fop != SLO_CHECK) Debug(sl, 0, "{}", GetSaveLoadErrorString() + 3);
3130 
3131  /* A saver/loader exception!! reinitialize all variables to prevent crash! */
3132  return (fop == SLO_LOAD) ? SL_REINIT : SL_ERROR;
3133  }
3134 }
3135 
3142 {
3143  std::string filename;
3144 
3146  filename = GenerateDefaultSaveName() + counter.Extension();
3147  } else {
3148  filename = counter.Filename();
3149  }
3150 
3151  Debug(sl, 2, "Autosaving to '{}'", filename);
3152  if (SaveOrLoad(filename, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR) != SL_OK) {
3153  ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
3154  }
3155 }
3156 
3157 
3160 {
3162 }
3163 
3168 {
3169  /* Check if we have a name for this map, which is the name of the first
3170  * available company. When there's no company available we'll use
3171  * 'Spectator' as "company" name. */
3172  CompanyID cid = _local_company;
3173  if (!Company::IsValidID(cid)) {
3174  for (const Company *c : Company::Iterate()) {
3175  cid = c->index;
3176  break;
3177  }
3178  }
3179 
3180  SetDParam(0, cid);
3181 
3182  /* We show the current game time differently depending on the timekeeping units used by this game. */
3184  /* Insert time played. */
3185  const auto play_time = TimerGameTick::counter / Ticks::TICKS_PER_SECOND;
3186  SetDParam(1, STR_SAVEGAME_DURATION_REALTIME);
3187  SetDParam(2, play_time / 60 / 60);
3188  SetDParam(3, (play_time / 60) % 60);
3189  } else {
3190  /* Insert current date */
3192  case 0: SetDParam(1, STR_JUST_DATE_LONG); break;
3193  case 1: SetDParam(1, STR_JUST_DATE_TINY); break;
3194  case 2: SetDParam(1, STR_JUST_DATE_ISO); break;
3195  default: NOT_REACHED();
3196  }
3198  }
3199 
3200  /* Get the correct string (special string for when there's not company) */
3201  std::string filename = GetString(!Company::IsValidID(cid) ? STR_SAVEGAME_NAME_SPECTATOR : STR_SAVEGAME_NAME_DEFAULT);
3202  SanitizeFilename(filename);
3203  return filename;
3204 }
3205 
3211 {
3213 }
3214 
3222 {
3223  if (aft == FT_INVALID || aft == FT_NONE) {
3224  this->file_op = SLO_INVALID;
3225  this->detail_ftype = DFT_INVALID;
3226  this->abstract_ftype = FT_INVALID;
3227  return;
3228  }
3229 
3230  this->file_op = fop;
3231  this->detail_ftype = dft;
3232  this->abstract_ftype = aft;
3233 }
3234 
3240 {
3241  this->SetMode(item.type);
3242  this->name = item.name;
3243  this->title = item.title;
3244 }
3245 
3247 {
3248  assert(this->load_description.has_value());
3249  return *this->load_description;
3250 }
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:2377
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:2708
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
SaveLoadFormat::init_write
SaveFilter *(* init_write)(SaveFilter *chain, byte compression)
Constructor for the save filter.
Definition: saveload.cpp:2617
FileWriter::FileWriter
FileWriter(FILE *file)
Create the file writer, so it writes to a specific file.
Definition: saveload.cpp:2208
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:2546
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:2244
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:2756
ZlibLoadFilter::~ZlibLoadFilter
~ZlibLoadFilter()
Clean everything up.
Definition: saveload.cpp:2390
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
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:2619
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
LZMALoadFilter::LZMALoadFilter
LZMALoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2510
LZMASaveFilter::LZMASaveFilter
LZMASaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2554
NoCompLoadFilter
Filter without any compression.
Definition: saveload.cpp:2334
_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:2504
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
SaveLoadFormat::init_load
LoadFilter *(* init_load)(LoadFilter *chain)
Constructor for the load filter.
Definition: saveload.cpp:2616
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:3159
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
NoCompLoadFilter::NoCompLoadFilter
NoCompLoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2341
LZOSaveFilter::LZOSaveFilter
LZOSaveFilter(SaveFilter *chain, byte)
Initialise this filter.
Definition: saveload.cpp:2299
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:2183
_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:3050
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
_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
LZOLoadFilter::LZOLoadFilter
LZOLoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2252
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
ZlibLoadFilter::ZlibLoadFilter
ZlibLoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload.cpp:2383
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:2547
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:2621
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:2257
SaveLoadHandler::GetLoadDescription
SaveLoadTable GetLoadDescription() const
Get the description for how to load the chunk.
Definition: saveload.cpp:3246
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
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
SaveLoadParams::reader
ReadBuffer * reader
Savegame reading buffer.
Definition: saveload.cpp:204
ZlibLoadFilter
Filter using Zlib compression.
Definition: saveload.cpp:2373
LoadWithFilter
SaveOrLoadResult LoadWithFilter(LoadFilter *reader)
Load the game using a (reader) filter.
Definition: saveload.cpp:3030
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:2571
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:2620
SaveLoadAction
SaveLoadAction
What are we currently doing?
Definition: saveload.cpp:69
LoadFilter::Reset
virtual void Reset()
Reset this filter to read from the beginning of the file.
Definition: saveload_filter.h:43
SaveLoadParams::sf
SaveFilter * sf
Filter to write the savegame to.
Definition: saveload.cpp:202
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:2345
ZlibSaveFilter::z
z_stream z
Stream state we are writing to.
Definition: saveload.cpp:2418
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
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
ReadBuffer::reader
LoadFilter * reader
The filter used to actually read.
Definition: saveload.cpp:91
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:2350
REF_STATION
@ REF_STATION
Load/save a reference to a station.
Definition: saveload.h:582
LZMALoadFilter
Filter without any compression.
Definition: saveload.cpp:2502
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
AbstractFileType
AbstractFileType
The different abstract types of files that the system knows about.
Definition: fileio_type.h:16
LoadFilter::Read
virtual size_t Read(byte *buf, size_t len)=0
Read a given number of bytes from the savegame.
ReferenceToInt
static size_t ReferenceToInt(const void *obj, SLRefType rt)
Pointers cannot be saved to a savegame, so this functions gets the index of the item,...
Definition: saveload.cpp:1094
SaveLoadFormat
The format for a reader/writer type of a savegame.
Definition: saveload.cpp:2610
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:2202
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
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:2743
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:2773
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
Filter using Zlib compression.
Definition: saveload.cpp:2417
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
SaveFilter::Finish
virtual void Finish()
Prepare everything to finish writing the savegame.
Definition: saveload_filter.h:88
ChunkHandler::Save
virtual void Save() const
Save the chunk.
Definition: saveload.h: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
LZMASaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2591
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:2762
ZlibLoadFilter::Read
size_t Read(byte *buf, size_t size) override
Read a given number of bytes from the savegame.
Definition: saveload.cpp:2395
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
SaveFilter::Write
virtual void Write(byte *buf, size_t len)=0
Write a given number of bytes into the savegame.
PersistentStorage
Class for pooled persistent storage of data.
Definition: newgrf_storage.h: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
ZlibSaveFilter::ZlibSaveFilter
ZlibSaveFilter(SaveFilter *chain, byte compression_level)
Initialise this filter.
Definition: saveload.cpp:2426
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
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:2444
FileWriter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2221
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:2659
SaveLoadParams::lf
LoadFilter * lf
Filter to read the savegame from.
Definition: saveload.cpp:205
NoCompSaveFilter::NoCompSaveFilter
NoCompSaveFilter(SaveFilter *chain, byte)
Initialise this filter.
Definition: saveload.cpp:2355
NoCompSaveFilter::Write
void Write(byte *buf, size_t size) override
Write a given number of bytes into the savegame.
Definition: saveload.cpp:2359
_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:2784
SaveLoadFormat::name
const char * name
name of the compressor/decompressor (debug-only)
Definition: saveload.cpp:2613
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:3167
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
MemoryDumper::Flush
void Flush(SaveFilter *writer)
Flush this dumper into a writer.
Definition: saveload.cpp:165
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:2734
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
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:3141
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
DoSave
static SaveOrLoadResult DoSave(SaveFilter *writer, bool threaded)
Actually perform the saving of the savegame.
Definition: saveload.cpp:2842
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:2503
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
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:2472
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
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:2376
LZMALoadFilter::~LZMALoadFilter
~LZMALoadFilter()
Clean everything up.
Definition: saveload.cpp:2517
ReadBuffer::ReadBuffer
ReadBuffer(LoadFilter *reader)
Initialise our variables.
Definition: saveload.cpp:98
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
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:2522
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
DoLoad
static SaveOrLoadResult DoLoad(LoadFilter *reader, bool load_check)
Actually perform the loading of a "non-old" savegame.
Definition: saveload.cpp:2891
ZlibSaveFilter::fwrite_buf
byte fwrite_buf[MEMORY_CHUNK_SIZE]
Buffer for writing to the file.
Definition: saveload.cpp:2419
_saveload_formats
static const SaveLoadFormat _saveload_formats[]
The different saveload formats known/understood by OpenTTD.
Definition: saveload.cpp:2623
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:2191
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:3239
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:60
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
SaveWithFilter
SaveOrLoadResult SaveWithFilter(SaveFilter *writer, bool threaded)
Save the game using a (writer) filter.
Definition: saveload.cpp:2874
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:2477
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:2294
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:2560
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:2614
SlWriteSimpleGamma
static void SlWriteSimpleGamma(size_t i)
Write the header descriptor of an object or an array.
Definition: saveload.cpp:505
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
SaveFilter::chain
SaveFilter * chain
Chained to the (savegame) filters.
Definition: saveload_filter.h:62
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
SaveLoadParams::dumper
MemoryDumper * dumper
Memory dumper to write the savegame to.
Definition: saveload.cpp:201
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:2247
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:2596
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:2433
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:2545
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:3210
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:2304
ClearSaveLoadState
static void ClearSaveLoadState()
Clear/free saveload state.
Definition: saveload.cpp:2718
LoadFilter::chain
LoadFilter * chain
Chained to the (savegame) filters.
Definition: saveload_filter.h:16
LoadFilter::LoadFilter
LoadFilter(LoadFilter *chain)
Initialise this filter.
Definition: saveload_filter.h:22
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h: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
_lzma_init
static const lzma_stream _lzma_init
Have a copy of an initialised LZMA stream.
Definition: saveload.cpp:2499
SLE_VAR_NAME
@ SLE_VAR_NAME
old custom name to be converted to a char pointer
Definition: saveload.h:635
FileWriter::~FileWriter
~FileWriter()
Make sure everything is cleaned up.
Definition: saveload.cpp:2213
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:2229
FileToSaveLoad::file_op
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:391
FileWriter
Yes, simply writing to a file.
Definition: saveload.cpp:2201
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
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