4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
12 * All actions handling saving and loading goes on in this file. The general actions
13 * are as follows for saving a game (loading is analogous):
15 * <li>initialize the writer by creating a temporary memory-buffer for it
16 * <li>go through all to-be saved elements, each 'chunk' (#ChunkHandler) prefixed by a label
17 * <li>use their description array (#SaveLoad) to know what elements to save and in what version
18 * of the game it was active (used when loading)
19 * <li>write all data byte-by-byte to the temporary buffer so it is endian-safe
20 * <li>when the buffer is full; flush it to the output (eg save to file) (_sl.buf, _sl.bufp, _sl.bufe)
21 * <li>repeat this until everything is done, and flush any remaining output to file
24 #include "../stdafx.h"
26 #include "../station_base.h"
27 #include "../dock_base.h"
28 #include "../thread/thread.h"
30 #include "../network/network.h"
31 #include "../window_func.h"
32 #include "../strings_func.h"
33 #include "../core/endian_func.hpp"
34 #include "../vehicle_base.h"
35 #include "../company_func.h"
36 #include "../date_func.h"
37 #include "../autoreplace_base.h"
38 #include "../roadstop_base.h"
39 #include "../linkgraph/linkgraph.h"
40 #include "../linkgraph/linkgraphjob.h"
41 #include "../statusbar_gui.h"
42 #include "../fileio_func.h"
43 #include "../gamelog.h"
44 #include "../string_func.h"
45 #include "../string_func_extra.h"
49 #include "../tbtr_template_vehicle.h"
51 #include "table/strings.h"
53 #include "saveload_internal.h"
54 #include "saveload_filter.h"
56 #include "../safeguards.h"
62 * Previous savegame versions, the trunk revision where they were
63 * introduced and the released version that had that particular
65 * Up to savegame version 18 there is a minor version as well.
72 * 4.1 122 0.3.3, 0.3.4
88 * 13.1 2080 0.4.0, 0.4.0.1
250 * 173 23967 1.2.0-RC1
271 * 194 26881 1.5.x, 1.6.0
277 * 256 SL_PATCH_PACK_DAYLENGTH
278 * 257 SL_PATCH_PACK_TOWN_BUILDINGS
279 * 258 SL_PATCH_PACK_MAP_FEATURES
280 * 259 SL_PATCH_PACK_SAFE_WAITING_LOCATION
281 * 260 SL_PATCH_PACK_1_2
282 * 261 SL_PATCH_PACK_1_3
283 * 262 SL_PATCH_PACK_1_4
284 * 263 SL_PATCH_PACK_1_5
285 * 264 SL_PATCH_PACK_1_6
286 * 265 SL_PATCH_PACK_1_7
287 * 266 SL_PATCH_PACK_1_8
288 * 267 SL_PATCH_PACK_1_9
289 * 268 SL_PATCH_PACK_1_10
290 * 269 SL_PATCH_PACK_1_11
291 * 270 SL_PATCH_PACK_1_12
292 * 271 SL_PATCH_PACK_1_14
293 * 272 SL_PATCH_PACK_1_15
294 * 273 SL_PATCH_PACK_1_16
295 * 274 SL_PATCH_PACK_1_18
296 * 275 SL_PATCH_PACK_1_18_3
297 * 276 SL_PATCH_PACK_1_18_4
298 * 277 SL_PATCH_PACK_1_18_6
299 * 278 SL_PATCH_PACK_1_19
300 * 279 SL_PATCH_PACK_1_20
301 * 280 SL_PATCH_PACK_1_21
302 * 281 SL_PATCH_PACK_1_22
303 * 282 SL_PATCH_PACK_1_23
305 extern const uint16 SAVEGAME_VERSION
= SL_PATCH_PACK_1_23
; ///< Current savegame version of OpenTTD.
307 SavegameType _savegame_type
; ///< type of savegame we are loading
308 FileToSaveLoad _file_to_saveload
; ///< File to save or load in the openttd loop.
310 uint32 _ttdp_version
; ///< version of TTDP savegame (if applicable)
311 uint16 _sl_version
; ///< the major savegame version identifier
312 byte _sl_minor_version
; ///< the minor savegame version, DO NOT USE!
313 char _savegame_format
[8]; ///< how to compress savegames
314 bool _do_autosave
; ///< are we doing an autosave at the moment?
316 /** What are we currently doing? */
317 enum SaveLoadAction
{
318 SLA_LOAD
, ///< loading
319 SLA_SAVE
, ///< saving
320 SLA_PTRS
, ///< fixing pointers
321 SLA_NULL
, ///< null all pointers (on loading error)
322 SLA_LOAD_CHECK
, ///< partial loading into #_load_check_data
326 NL_NONE
= 0, ///< not working in NeedLength mode
327 NL_WANTLENGTH
= 1, ///< writing length and data
328 NL_CALCLENGTH
= 2, ///< need to calculate the length
331 /** Save in chunks of 128 KiB. */
332 static const size_t MEMORY_CHUNK_SIZE
= 128 * 1024;
334 /** A buffer for reading (and buffering) savegame data. */
336 byte buf
[MEMORY_CHUNK_SIZE
]; ///< Buffer we're going to read from.
337 byte
*bufp
; ///< Location we're at reading the buffer.
338 byte
*bufe
; ///< End of the buffer we can read from.
339 LoadFilter
*reader
; ///< The filter used to actually read.
340 size_t read
; ///< The amount of read bytes so far from the filter.
343 * Initialise our variables.
344 * @param reader The filter to actually read data.
346 ReadBuffer(LoadFilter
*reader
) : bufp(NULL
), bufe(NULL
), reader(reader
), read(0)
350 inline byte
ReadByte()
352 if (this->bufp
== this->bufe
) {
353 size_t len
= this->reader
->Read(this->buf
, lengthof(this->buf
));
354 if (len
== 0) SlErrorCorrupt("Unexpected end of chunk");
357 this->bufp
= this->buf
;
358 this->bufe
= this->buf
+ len
;
361 return *this->bufp
++;
365 * Get the size of the memory dump made so far.
368 size_t GetSize() const
370 return this->read
- (this->bufe
- this->bufp
);
375 /** Container for dumping the savegame (quickly) to memory. */
376 struct MemoryDumper
{
377 AutoFreeSmallVector
<byte
*, 16> blocks
; ///< Buffer with blocks of allocated memory.
378 byte
*buf
; ///< Buffer we're going to write to.
379 byte
*bufe
; ///< End of the buffer we write to.
381 /** Initialise our variables. */
382 MemoryDumper() : buf(NULL
), bufe(NULL
)
387 * Write a single byte into the dumper.
388 * @param b The byte to write.
390 inline void WriteByte(byte b
)
392 /* Are we at the end of this chunk? */
393 if (this->buf
== this->bufe
) {
394 this->buf
= CallocT
<byte
>(MEMORY_CHUNK_SIZE
);
395 *this->blocks
.Append() = this->buf
;
396 this->bufe
= this->buf
+ MEMORY_CHUNK_SIZE
;
403 * Flush this dumper into a writer.
404 * @param writer The filter we want to use.
406 void Flush(SaveFilter
*writer
)
409 size_t t
= this->GetSize();
412 size_t to_write
= min(MEMORY_CHUNK_SIZE
, t
);
414 writer
->Write(this->blocks
[i
++], to_write
);
422 * Get the size of the memory dump made so far.
425 size_t GetSize() const
427 return this->blocks
.Length() * MEMORY_CHUNK_SIZE
- (this->bufe
- this->buf
);
431 /** The saveload struct, containing reader-writer functions, buffer, version, etc. */
432 struct SaveLoadParams
{
433 SaveLoadAction action
; ///< are we doing a save or a load atm.
434 NeedLength need_length
; ///< working in NeedLength (Autolength) mode?
435 byte block_mode
; ///< ???
436 bool error
; ///< did an error occur or not
438 size_t obj_len
; ///< the length of the current object we are busy with
439 int array_index
, last_array_index
; ///< in the case of an array, the current and last positions
441 MemoryDumper
*dumper
; ///< Memory dumper to write the savegame to.
442 SaveFilter
*sf
; ///< Filter to write the savegame to.
444 ReadBuffer
*reader
; ///< Savegame reading buffer.
445 LoadFilter
*lf
; ///< Filter to read the savegame from.
447 StringID error_str
; ///< the translatable error message to show
448 char *extra_msg
; ///< the error message
450 byte ff_state
; ///< The state of fast-forward when saving started.
451 bool saveinprogress
; ///< Whether there is currently a save in progress.
454 static SaveLoadParams _sl
; ///< Parameters used for/at saveload.
456 /* these define the chunks */
457 extern const ChunkHandler _gamelog_chunk_handlers
[];
458 extern const ChunkHandler _map_chunk_handlers
[];
459 extern const ChunkHandler _misc_chunk_handlers
[];
460 extern const ChunkHandler _name_chunk_handlers
[];
461 extern const ChunkHandler _cheat_chunk_handlers
[] ;
462 extern const ChunkHandler _setting_chunk_handlers
[];
463 extern const ChunkHandler _company_chunk_handlers
[];
464 extern const ChunkHandler _engine_chunk_handlers
[];
465 extern const ChunkHandler _veh_chunk_handlers
[];
466 extern const ChunkHandler _waypoint_chunk_handlers
[];
467 extern const ChunkHandler _depot_chunk_handlers
[];
468 extern const ChunkHandler _order_chunk_handlers
[];
469 extern const ChunkHandler _town_chunk_handlers
[];
470 extern const ChunkHandler _sign_chunk_handlers
[];
471 extern const ChunkHandler _station_chunk_handlers
[];
472 extern const ChunkHandler _industry_chunk_handlers
[];
473 extern const ChunkHandler _economy_chunk_handlers
[];
474 extern const ChunkHandler _subsidy_chunk_handlers
[];
475 extern const ChunkHandler _cargomonitor_chunk_handlers
[];
476 extern const ChunkHandler _goal_chunk_handlers
[];
477 extern const ChunkHandler _story_page_chunk_handlers
[];
478 extern const ChunkHandler _ai_chunk_handlers
[];
479 extern const ChunkHandler _game_chunk_handlers
[];
480 extern const ChunkHandler _animated_tile_chunk_handlers
[];
481 extern const ChunkHandler _newgrf_chunk_handlers
[];
482 extern const ChunkHandler _group_chunk_handlers
[];
483 extern const ChunkHandler _cargopacket_chunk_handlers
[];
484 extern const ChunkHandler _autoreplace_chunk_handlers
[];
485 extern const ChunkHandler _labelmaps_chunk_handlers
[];
486 extern const ChunkHandler _linkgraph_chunk_handlers
[];
487 extern const ChunkHandler _airport_chunk_handlers
[];
488 extern const ChunkHandler _object_chunk_handlers
[];
489 extern const ChunkHandler _persistent_storage_chunk_handlers
[];
490 extern const ChunkHandler _plan_chunk_handlers
[];
491 extern const ChunkHandler _trace_restrict_chunk_handlers
[];
492 extern const ChunkHandler _template_replacement_chunk_handlers
[];
493 extern const ChunkHandler _template_vehicle_chunk_handlers
[];
494 extern const ChunkHandler _logic_signal_handlers
[];
495 extern const ChunkHandler _bridge_signal_chunk_handlers
[];
496 extern const ChunkHandler _tunnel_chunk_handlers
[];
498 /** Array of all chunks in a savegame, \c NULL terminated. */
499 static const ChunkHandler
* const _chunk_handlers
[] = {
500 _gamelog_chunk_handlers
,
502 _misc_chunk_handlers
,
503 _name_chunk_handlers
,
504 _cheat_chunk_handlers
,
505 _setting_chunk_handlers
,
507 _waypoint_chunk_handlers
,
508 _depot_chunk_handlers
,
509 _order_chunk_handlers
,
510 _industry_chunk_handlers
,
511 _economy_chunk_handlers
,
512 _subsidy_chunk_handlers
,
513 _cargomonitor_chunk_handlers
,
514 _goal_chunk_handlers
,
515 _story_page_chunk_handlers
,
516 _engine_chunk_handlers
,
517 _town_chunk_handlers
,
518 _sign_chunk_handlers
,
519 _station_chunk_handlers
,
520 _company_chunk_handlers
,
522 _game_chunk_handlers
,
523 _animated_tile_chunk_handlers
,
524 _newgrf_chunk_handlers
,
525 _group_chunk_handlers
,
526 _cargopacket_chunk_handlers
,
527 _autoreplace_chunk_handlers
,
528 _labelmaps_chunk_handlers
,
529 _linkgraph_chunk_handlers
,
530 _airport_chunk_handlers
,
531 _object_chunk_handlers
,
532 _persistent_storage_chunk_handlers
,
533 _plan_chunk_handlers
,
534 _trace_restrict_chunk_handlers
,
535 _template_replacement_chunk_handlers
,
536 _template_vehicle_chunk_handlers
,
537 _logic_signal_handlers
,
538 _bridge_signal_chunk_handlers
,
539 _tunnel_chunk_handlers
,
544 * Iterate over all chunk handlers.
545 * @param ch the chunk handler iterator
547 #define FOR_ALL_CHUNK_HANDLERS(ch) \
548 for (const ChunkHandler * const *chsc = _chunk_handlers; *chsc != NULL; chsc++) \
549 for (const ChunkHandler *ch = *chsc; ch != NULL; ch = (ch->flags & CH_LAST) ? NULL : ch + 1)
551 /** Null all pointers (convert index -> NULL) */
552 static void SlNullPointers()
554 _sl
.action
= SLA_NULL
;
556 /* We don't want any savegame conversion code to run
557 * during NULLing; especially those that try to get
558 * pointers from other pools. */
559 _sl_version
= SAVEGAME_VERSION
;
561 DEBUG(sl
, 1, "Nulling pointers");
563 FOR_ALL_CHUNK_HANDLERS(ch
) {
564 if (ch
->ptrs_proc
!= NULL
) {
565 DEBUG(sl
, 2, "Nulling pointers for %c%c%c%c", ch
->id
>> 24, ch
->id
>> 16, ch
->id
>> 8, ch
->id
);
570 DEBUG(sl
, 1, "All pointers nulled");
572 assert(_sl
.action
== SLA_NULL
);
576 * Error handler. Sets everything up to show an error message and to clean
577 * up the mess of a partial savegame load.
578 * @param string The translatable error message to show.
579 * @param extra_msg An extra error message coming from one of the APIs.
580 * @note This function does never return as it throws an exception to
581 * break out of all the saveload code.
583 void NORETURN
SlError(StringID string
, const char *extra_msg
)
585 /* Distinguish between loading into _load_check_data vs. normal save/load. */
586 if (_sl
.action
== SLA_LOAD_CHECK
) {
587 _load_check_data
.error
= string
;
588 free(_load_check_data
.error_data
);
589 _load_check_data
.error_data
= (extra_msg
== NULL
) ? NULL
: stredup(extra_msg
);
591 _sl
.error_str
= string
;
593 _sl
.extra_msg
= (extra_msg
== NULL
) ? NULL
: stredup(extra_msg
);
596 /* We have to NULL all pointers here; we might be in a state where
597 * the pointers are actually filled with indices, which means that
598 * when we access them during cleaning the pool dereferences of
599 * those indices will be made with segmentation faults as result. */
600 if (_sl
.action
== SLA_LOAD
|| _sl
.action
== SLA_PTRS
) SlNullPointers();
601 throw std::exception();
605 * Error handler for corrupt savegames. Sets everything up to show the
606 * error message and to clean up the mess of a partial savegame load.
607 * @param msg Location the corruption has been spotted.
608 * @note This function does never return as it throws an exception to
609 * break out of all the saveload code.
611 void NORETURN
SlErrorCorrupt(const char *msg
)
613 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME
, msg
);
617 typedef void (*AsyncSaveFinishProc
)(); ///< Callback for when the savegame loading is finished.
618 static AsyncSaveFinishProc _async_save_finish
= NULL
; ///< Callback to call when the savegame loading is finished.
619 static ThreadObject
*_save_thread
; ///< The thread we're using to compress and write a savegame
622 * Called by save thread to tell we finished saving.
623 * @param proc The callback to call when saving is done.
625 static void SetAsyncSaveFinish(AsyncSaveFinishProc proc
)
627 if (_exit_game
) return;
628 while (_async_save_finish
!= NULL
) CSleep(10);
630 _async_save_finish
= proc
;
634 * Handle async save finishes.
636 void ProcessAsyncSaveFinish()
638 if (_async_save_finish
== NULL
) return;
640 _async_save_finish();
642 _async_save_finish
= NULL
;
644 if (_save_thread
!= NULL
) {
645 _save_thread
->Join();
652 * Wrapper for reading a byte from the buffer.
653 * @return The read byte.
657 return _sl
.reader
->ReadByte();
661 * Wrapper for writing a byte to the dumper.
662 * @param b The byte to write.
664 void SlWriteByte(byte b
)
666 _sl
.dumper
->WriteByte(b
);
669 static inline int SlReadUint16()
671 int x
= SlReadByte() << 8;
672 return x
| SlReadByte();
675 static inline uint32
SlReadUint32()
677 uint32 x
= SlReadUint16() << 16;
678 return x
| SlReadUint16();
681 static inline uint64
SlReadUint64()
683 uint32 x
= SlReadUint32();
684 uint32 y
= SlReadUint32();
685 return (uint64
)x
<< 32 | y
;
688 static inline void SlWriteUint16(uint16 v
)
690 SlWriteByte(GB(v
, 8, 8));
691 SlWriteByte(GB(v
, 0, 8));
694 static inline void SlWriteUint32(uint32 v
)
696 SlWriteUint16(GB(v
, 16, 16));
697 SlWriteUint16(GB(v
, 0, 16));
700 static inline void SlWriteUint64(uint64 x
)
702 SlWriteUint32((uint32
)(x
>> 32));
703 SlWriteUint32((uint32
)x
);
707 * Read in bytes from the file/data structure but don't do
708 * anything with them, discarding them in effect
709 * @param length The amount of bytes that is being treated this way
711 static inline void SlSkipBytes(size_t length
)
713 for (; length
!= 0; length
--) SlReadByte();
717 * Read in the header descriptor of an object or an array.
718 * If the highest bit is set (7), then the index is bigger than 127
719 * elements, so use the next byte to read in the real value.
720 * The actual value is then both bytes added with the first shifted
721 * 8 bits to the left, and dropping the highest bit (which only indicated a big index).
722 * x = ((x & 0x7F) << 8) + SlReadByte();
723 * @return Return the value of the index
725 static uint
SlReadSimpleGamma()
727 uint i
= SlReadByte();
737 SlErrorCorrupt("Unsupported gamma");
739 i
= SlReadByte(); // 32 bits only.
741 i
= (i
<< 8) | SlReadByte();
743 i
= (i
<< 8) | SlReadByte();
745 i
= (i
<< 8) | SlReadByte();
751 * Write the header descriptor of an object or an array.
752 * If the element is bigger than 127, use 2 bytes for saving
753 * and use the highest byte of the first written one as a notice
754 * that the length consists of 2 bytes, etc.. like this:
757 * 110xxxxx xxxxxxxx xxxxxxxx
758 * 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
759 * 11110--- xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
760 * We could extend the scheme ad infinum to support arbitrarily
761 * large chunks, but as sizeof(size_t) == 4 is still very common
762 * we don't support anything above 32 bits. That's why in the last
763 * case the 3 most significant bits are unused.
764 * @param i Index being written
767 static void SlWriteSimpleGamma(size_t i
)
770 if (i
>= (1 << 14)) {
771 if (i
>= (1 << 21)) {
772 if (i
>= (1 << 28)) {
773 assert(i
<= UINT32_MAX
); // We can only support 32 bits for now.
774 SlWriteByte((byte
)(0xF0));
775 SlWriteByte((byte
)(i
>> 24));
777 SlWriteByte((byte
)(0xE0 | (i
>> 24)));
779 SlWriteByte((byte
)(i
>> 16));
781 SlWriteByte((byte
)(0xC0 | (i
>> 16)));
783 SlWriteByte((byte
)(i
>> 8));
785 SlWriteByte((byte
)(0x80 | (i
>> 8)));
788 SlWriteByte((byte
)i
);
791 /** Return how many bytes used to encode a gamma value */
792 static inline uint
SlGetGammaLength(size_t i
)
794 return 1 + (i
>= (1 << 7)) + (i
>= (1 << 14)) + (i
>= (1 << 21)) + (i
>= (1 << 28));
797 static inline uint
SlReadSparseIndex()
799 return SlReadSimpleGamma();
802 static inline void SlWriteSparseIndex(uint index
)
804 SlWriteSimpleGamma(index
);
807 static inline uint
SlReadArrayLength()
809 return SlReadSimpleGamma();
812 static inline void SlWriteArrayLength(size_t length
)
814 SlWriteSimpleGamma(length
);
817 static inline uint
SlGetArrayLength(size_t length
)
819 return SlGetGammaLength(length
);
823 * Return the size in bytes of a certain type of normal/atomic variable
824 * as it appears in memory. See VarTypes
825 * @param conv VarType type of variable that is used for calculating the size
826 * @return Return the size of this type in bytes
828 static inline uint
SlCalcConvMemLen(VarType conv
)
830 static const byte conv_mem_size
[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
831 byte length
= GB(conv
, 4, 4);
833 switch (length
<< 4) {
838 return SlReadArrayLength();
841 assert(length
< lengthof(conv_mem_size
));
842 return conv_mem_size
[length
];
847 * Return the size in bytes of a certain type of normal/atomic variable
848 * as it appears in a saved game. See VarTypes
849 * @param conv VarType type of variable that is used for calculating the size
850 * @return Return the size of this type in bytes
852 static inline byte
SlCalcConvFileLen(VarType conv
)
854 static const byte conv_file_size
[] = {1, 1, 2, 2, 4, 4, 8, 8, 2};
855 byte length
= GB(conv
, 0, 4);
856 assert(length
< lengthof(conv_file_size
));
857 return conv_file_size
[length
];
860 /** Return the size in bytes of a reference (pointer) */
861 static inline size_t SlCalcRefLen()
863 return IsSavegameVersionBefore(69) ? 2 : 4;
866 void SlSetArrayIndex(uint index
)
868 _sl
.need_length
= NL_WANTLENGTH
;
869 _sl
.array_index
= index
;
872 static size_t _next_offs
;
875 * Iterate through the elements of an array and read the whole thing
876 * @return The index of the object, or -1 if we have reached the end of current block
882 /* After reading in the whole array inside the loop
883 * we must have read in all the data, so we must be at end of current block. */
884 if (_next_offs
!= 0 && _sl
.reader
->GetSize() != _next_offs
) SlErrorCorrupt("Invalid chunk size");
887 uint length
= SlReadArrayLength();
893 _sl
.obj_len
= --length
;
894 _next_offs
= _sl
.reader
->GetSize() + length
;
896 switch (_sl
.block_mode
) {
897 case CH_SPARSE_ARRAY
: index
= (int)SlReadSparseIndex(); break;
898 case CH_ARRAY
: index
= _sl
.array_index
++; break;
900 DEBUG(sl
, 0, "SlIterateArray error");
904 if (length
!= 0) return index
;
909 * Skip an array or sparse array
913 while (SlIterateArray() != -1) {
914 SlSkipBytes(_next_offs
- _sl
.reader
->GetSize());
919 * Sets the length of either a RIFF object or the number of items in an array.
920 * This lets us load an object or an array of arbitrary size
921 * @param length The length of the sought object/array
923 void SlSetLength(size_t length
)
925 assert(_sl
.action
== SLA_SAVE
);
927 switch (_sl
.need_length
) {
929 _sl
.need_length
= NL_NONE
;
930 switch (_sl
.block_mode
) {
932 /* Ugly encoding of >16M RIFF chunks
933 * The lower 24 bits are normal
934 * The uppermost 4 bits are bits 24:27 */
935 assert(length
< (1 << 28));
936 SlWriteUint32((uint32
)((length
& 0xFFFFFF) | ((length
>> 24) << 28)));
939 assert(_sl
.last_array_index
<= _sl
.array_index
);
940 while (++_sl
.last_array_index
<= _sl
.array_index
) {
941 SlWriteArrayLength(1);
943 SlWriteArrayLength(length
+ 1);
945 case CH_SPARSE_ARRAY
:
946 SlWriteArrayLength(length
+ 1 + SlGetArrayLength(_sl
.array_index
)); // Also include length of sparse index.
947 SlWriteSparseIndex(_sl
.array_index
);
949 default: NOT_REACHED();
954 _sl
.obj_len
+= (int)length
;
957 default: NOT_REACHED();
962 * Save/Load bytes. These do not need to be converted to Little/Big Endian
963 * so directly write them or read them to/from file
964 * @param ptr The source or destination of the object being manipulated
965 * @param length number of bytes this fast CopyBytes lasts
967 static void SlCopyBytes(void *ptr
, size_t length
)
969 byte
*p
= (byte
*)ptr
;
971 switch (_sl
.action
) {
974 for (; length
!= 0; length
--) *p
++ = SlReadByte();
977 for (; length
!= 0; length
--) SlWriteByte(*p
++);
979 default: NOT_REACHED();
983 /** Get the length of the current object */
984 size_t SlGetFieldLength()
990 * Return a signed-long version of the value of a setting
991 * @param ptr pointer to the variable
992 * @param conv type of variable, can be a non-clean
993 * type, eg one with other flags because it is parsed
994 * @return returns the value of the pointer-setting
996 int64
ReadValue(const void *ptr
, VarType conv
)
998 switch (GetVarMemType(conv
)) {
999 case SLE_VAR_BL
: return (*(const bool *)ptr
!= 0);
1000 case SLE_VAR_I8
: return *(const int8
*)ptr
;
1001 case SLE_VAR_U8
: return *(const byte
*)ptr
;
1002 case SLE_VAR_I16
: return *(const int16
*)ptr
;
1003 case SLE_VAR_U16
: return *(const uint16
*)ptr
;
1004 case SLE_VAR_I32
: return *(const int32
*)ptr
;
1005 case SLE_VAR_U32
: return *(const uint32
*)ptr
;
1006 case SLE_VAR_I64
: return *(const int64
*)ptr
;
1007 case SLE_VAR_U64
: return *(const uint64
*)ptr
;
1008 case SLE_VAR_NULL
:return 0;
1009 default: NOT_REACHED();
1014 * Write the value of a setting
1015 * @param ptr pointer to the variable
1016 * @param conv type of variable, can be a non-clean type, eg
1017 * with other flags. It is parsed upon read
1018 * @param val the new value being given to the variable
1020 void WriteValue(void *ptr
, VarType conv
, int64 val
)
1022 switch (GetVarMemType(conv
)) {
1023 case SLE_VAR_BL
: *(bool *)ptr
= (val
!= 0); break;
1024 case SLE_VAR_I8
: *(int8
*)ptr
= val
; break;
1025 case SLE_VAR_U8
: *(byte
*)ptr
= val
; break;
1026 case SLE_VAR_I16
: *(int16
*)ptr
= val
; break;
1027 case SLE_VAR_U16
: *(uint16
*)ptr
= val
; break;
1028 case SLE_VAR_I32
: *(int32
*)ptr
= val
; break;
1029 case SLE_VAR_U32
: *(uint32
*)ptr
= val
; break;
1030 case SLE_VAR_I64
: *(int64
*)ptr
= val
; break;
1031 case SLE_VAR_U64
: *(uint64
*)ptr
= val
; break;
1032 case SLE_VAR_NAME
: *(char**)ptr
= CopyFromOldName(val
); break;
1033 case SLE_VAR_NULL
: break;
1034 default: NOT_REACHED();
1039 * Handle all conversion and typechecking of variables here.
1040 * In the case of saving, read in the actual value from the struct
1041 * and then write them to file, endian safely. Loading a value
1042 * goes exactly the opposite way
1043 * @param ptr The object being filled/read
1044 * @param conv VarType type of the current element of the struct
1046 static void SlSaveLoadConv(void *ptr
, VarType conv
)
1048 switch (_sl
.action
) {
1050 int64 x
= ReadValue(ptr
, conv
);
1052 /* Write the value to the file and check if its value is in the desired range */
1053 switch (GetVarFileType(conv
)) {
1054 case SLE_FILE_I8
: assert(x
>= -128 && x
<= 127); SlWriteByte(x
);break;
1055 case SLE_FILE_U8
: assert(x
>= 0 && x
<= 255); SlWriteByte(x
);break;
1056 case SLE_FILE_I16
:assert(x
>= -32768 && x
<= 32767); SlWriteUint16(x
);break;
1057 case SLE_FILE_STRINGID
:
1058 case SLE_FILE_U16
:assert(x
>= 0 && x
<= 65535); SlWriteUint16(x
);break;
1060 case SLE_FILE_U32
: SlWriteUint32((uint32
)x
);break;
1062 case SLE_FILE_U64
: SlWriteUint64(x
);break;
1063 default: NOT_REACHED();
1067 case SLA_LOAD_CHECK
:
1070 /* Read a value from the file */
1071 switch (GetVarFileType(conv
)) {
1072 case SLE_FILE_I8
: x
= (int8
)SlReadByte(); break;
1073 case SLE_FILE_U8
: x
= (byte
)SlReadByte(); break;
1074 case SLE_FILE_I16
: x
= (int16
)SlReadUint16(); break;
1075 case SLE_FILE_U16
: x
= (uint16
)SlReadUint16(); break;
1076 case SLE_FILE_I32
: x
= (int32
)SlReadUint32(); break;
1077 case SLE_FILE_U32
: x
= (uint32
)SlReadUint32(); break;
1078 case SLE_FILE_I64
: x
= (int64
)SlReadUint64(); break;
1079 case SLE_FILE_U64
: x
= (uint64
)SlReadUint64(); break;
1080 case SLE_FILE_STRINGID
: x
= RemapOldStringID((uint16
)SlReadUint16()); break;
1081 default: NOT_REACHED();
1084 /* Write The value to the struct. These ARE endian safe. */
1085 WriteValue(ptr
, conv
, x
);
1088 case SLA_PTRS
: break;
1089 case SLA_NULL
: break;
1090 default: NOT_REACHED();
1095 * Calculate the net length of a string. This is in almost all cases
1096 * just strlen(), but if the string is not properly terminated, we'll
1097 * resort to the maximum length of the buffer.
1098 * @param ptr pointer to the stringbuffer
1099 * @param length maximum length of the string (buffer). If -1 we don't care
1100 * about a maximum length, but take string length as it is.
1101 * @return return the net length of the string
1103 static inline size_t SlCalcNetStringLen(const char *ptr
, size_t length
)
1105 if (ptr
== NULL
) return 0;
1106 return min(strlen(ptr
), length
- 1);
1110 * Calculate the gross length of the std::string that it
1111 * will occupy in the savegame. This includes the real length,
1112 * and the length that the index will occupy.
1113 * @param str reference to the std::string
1114 * @return return the gross length of the string
1116 static inline size_t SlCalcStdStrLen(const std::string
&str
)
1118 return str
.size() + SlGetArrayLength(str
.size()); // also include the length of the index
1122 * Calculate the gross length of the string that it
1123 * will occupy in the savegame. This includes the real length, returned
1124 * by SlCalcNetStringLen and the length that the index will occupy.
1125 * @param ptr pointer to the stringbuffer
1126 * @param length maximum length of the string (buffer size, etc.)
1127 * @param conv type of data been used
1128 * @return return the gross length of the string
1130 static inline size_t SlCalcStringLen(const void *ptr
, size_t length
, VarType conv
)
1135 switch (GetVarMemType(conv
)) {
1136 default: NOT_REACHED();
1139 str
= *(const char * const *)ptr
;
1144 str
= (const char *)ptr
;
1149 len
= SlCalcNetStringLen(str
, len
);
1150 return len
+ SlGetArrayLength(len
); // also include the length of the index
1154 * Save/Load a string.
1155 * @param ptr the string being manipulated
1156 * @param length of the string (full length)
1157 * @param conv must be SLE_FILE_STRING
1159 static void SlString(void *ptr
, size_t length
, VarType conv
)
1161 switch (_sl
.action
) {
1164 switch (GetVarMemType(conv
)) {
1165 default: NOT_REACHED();
1168 len
= SlCalcNetStringLen((char *)ptr
, length
);
1172 ptr
= *(char **)ptr
;
1173 len
= SlCalcNetStringLen((char *)ptr
, SIZE_MAX
);
1177 SlWriteArrayLength(len
);
1178 SlCopyBytes(ptr
, len
);
1181 case SLA_LOAD_CHECK
:
1183 size_t len
= SlReadArrayLength();
1185 switch (GetVarMemType(conv
)) {
1186 default: NOT_REACHED();
1189 if (len
>= length
) {
1190 DEBUG(sl
, 1, "String length in savegame is bigger than buffer, truncating");
1191 SlCopyBytes(ptr
, length
);
1192 SlSkipBytes(len
- length
);
1195 SlCopyBytes(ptr
, len
);
1199 case SLE_VAR_STRQ
: // Malloc'd string, free previous incarnation, and allocate
1200 free(*(char **)ptr
);
1202 *(char **)ptr
= NULL
;
1205 *(char **)ptr
= MallocT
<char>(len
+ 1); // terminating '\0'
1206 ptr
= *(char **)ptr
;
1207 SlCopyBytes(ptr
, len
);
1212 ((char *)ptr
)[len
] = '\0'; // properly terminate the string
1213 StringValidationSettings settings
= SVS_REPLACE_WITH_QUESTION_MARK
;
1214 if ((conv
& SLF_ALLOW_CONTROL
) != 0) {
1215 settings
= settings
| SVS_ALLOW_CONTROL_CODE
;
1216 if (IsSavegameVersionBefore(169)) {
1217 str_fix_scc_encoded((char *)ptr
, (char *)ptr
+ len
);
1220 if ((conv
& SLF_ALLOW_NEWLINE
) != 0) {
1221 settings
= settings
| SVS_ALLOW_NEWLINE
;
1223 str_validate((char *)ptr
, (char *)ptr
+ len
, settings
);
1226 case SLA_PTRS
: break;
1227 case SLA_NULL
: break;
1228 default: NOT_REACHED();
1233 * Save/Load a std::string.
1234 * @param ptr the std::string being manipulated
1235 * @param conv must be SLE_FILE_STRING
1237 static void SlStdString(std::string
&str
, VarType conv
)
1239 switch (_sl
.action
) {
1241 SlWriteArrayLength(str
.size());
1242 SlCopyBytes(const_cast<char *>(str
.data()), str
.size());
1245 case SLA_LOAD_CHECK
:
1247 size_t len
= SlReadArrayLength();
1249 SlCopyBytes(const_cast<char *>(str
.c_str()), len
);
1251 StringValidationSettings settings
= SVS_REPLACE_WITH_QUESTION_MARK
;
1252 if ((conv
& SLF_ALLOW_CONTROL
) != 0) {
1253 settings
= settings
| SVS_ALLOW_CONTROL_CODE
;
1255 if ((conv
& SLF_ALLOW_NEWLINE
) != 0) {
1256 settings
= settings
| SVS_ALLOW_NEWLINE
;
1258 str_validate(str
, settings
);
1261 case SLA_PTRS
: break;
1262 case SLA_NULL
: break;
1263 default: NOT_REACHED();
1268 * Return the size in bytes of a certain type of atomic array
1269 * @param length The length of the array counted in elements
1270 * @param conv VarType type of the variable that is used in calculating the size
1272 static inline size_t SlCalcArrayLen(size_t length
, VarType conv
)
1274 return SlCalcConvFileLen(conv
) * length
;
1278 * Save/Load an array.
1279 * @param array The array being manipulated
1280 * @param length The length of the array in elements
1281 * @param conv VarType type of the atomic array (int, byte, uint64, etc.)
1283 void SlArray(void *array
, size_t length
, VarType conv
)
1285 if (_sl
.action
== SLA_PTRS
|| _sl
.action
== SLA_NULL
) return;
1287 /* Automatically calculate the length? */
1288 if (_sl
.need_length
!= NL_NONE
) {
1289 SlSetLength(SlCalcArrayLen(length
, conv
));
1290 /* Determine length only? */
1291 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1294 /* NOTICE - handle some buggy stuff, in really old versions everything was saved
1295 * as a byte-type. So detect this, and adjust array size accordingly */
1296 if (_sl
.action
!= SLA_SAVE
&& _sl_version
== 0) {
1297 /* all arrays except difficulty settings */
1298 if (conv
== SLE_INT16
|| conv
== SLE_UINT16
|| conv
== SLE_STRINGID
||
1299 conv
== SLE_INT32
|| conv
== SLE_UINT32
) {
1300 SlCopyBytes(array
, length
* SlCalcConvFileLen(conv
));
1303 /* used for conversion of Money 32bit->64bit */
1304 if (conv
== (SLE_FILE_I32
| SLE_VAR_I64
)) {
1305 for (uint i
= 0; i
< length
; i
++) {
1306 ((int64
*)array
)[i
] = (int32
)BSWAP32(SlReadUint32());
1312 /* If the size of elements is 1 byte both in file and memory, no special
1313 * conversion is needed, use specialized copy-copy function to speed up things */
1314 if (conv
== SLE_INT8
|| conv
== SLE_UINT8
) {
1315 SlCopyBytes(array
, length
);
1317 byte
*a
= (byte
*)array
;
1318 byte mem_size
= SlCalcConvMemLen(conv
);
1320 for (; length
!= 0; length
--) {
1321 SlSaveLoadConv(a
, conv
);
1322 a
+= mem_size
; // get size
1329 * Pointers cannot be saved to a savegame, so this functions gets
1330 * the index of the item, and if not available, it hussles with
1331 * pointers (looks really bad :()
1332 * Remember that a NULL item has value 0, and all
1333 * indices have +1, so vehicle 0 is saved as index 1.
1334 * @param obj The object that we want to get the index of
1335 * @param rt SLRefType type of the object the index is being sought of
1336 * @return Return the pointer converted to an index of the type pointed to
1338 static size_t ReferenceToInt(const void *obj
, SLRefType rt
)
1340 assert(_sl
.action
== SLA_SAVE
);
1342 if (obj
== NULL
) return 0;
1345 case REF_VEHICLE_OLD
: // Old vehicles we save as new ones
1346 case REF_VEHICLE
: return ((const Vehicle
*)obj
)->index
+ 1;
1347 case REF_TEMPLATE_VEHICLE
: return ((const TemplateVehicle
*)obj
)->index
+ 1;
1348 case REF_STATION
: return ((const Station
*)obj
)->index
+ 1;
1349 case REF_TOWN
: return ((const Town
*)obj
)->index
+ 1;
1350 case REF_ORDER
: return ((const Order
*)obj
)->index
+ 1;
1351 case REF_ROADSTOPS
: return ((const RoadStop
*)obj
)->index
+ 1;
1352 case REF_ENGINE_RENEWS
: return ((const EngineRenew
*)obj
)->index
+ 1;
1353 case REF_CARGO_PACKET
: return ((const CargoPacket
*)obj
)->index
+ 1;
1354 case REF_ORDERLIST
: return ((const OrderList
*)obj
)->index
+ 1;
1355 case REF_STORAGE
: return ((const PersistentStorage
*)obj
)->index
+ 1;
1356 case REF_LINK_GRAPH
: return ((const LinkGraph
*)obj
)->index
+ 1;
1357 case REF_LINK_GRAPH_JOB
: return ((const LinkGraphJob
*)obj
)->index
+ 1;
1358 case REF_DOCKS
: return ((const Dock
*)obj
)->index
+ 1;
1359 default: NOT_REACHED();
1364 * Pointers cannot be loaded from a savegame, so this function
1365 * gets the index from the savegame and returns the appropriate
1366 * pointer from the already loaded base.
1367 * Remember that an index of 0 is a NULL pointer so all indices
1368 * are +1 so vehicle 0 is saved as 1.
1369 * @param index The index that is being converted to a pointer
1370 * @param rt SLRefType type of the object the pointer is sought of
1371 * @return Return the index converted to a pointer of any type
1373 static void *IntToReference(size_t index
, SLRefType rt
)
1375 assert_compile(sizeof(size_t) <= sizeof(void *));
1377 assert(_sl
.action
== SLA_PTRS
);
1379 /* After version 4.3 REF_VEHICLE_OLD is saved as REF_VEHICLE,
1380 * and should be loaded like that */
1381 if (rt
== REF_VEHICLE_OLD
&& !IsSavegameVersionBefore(4, 4)) {
1385 /* No need to look up NULL pointers, just return immediately */
1386 if (index
== (rt
== REF_VEHICLE_OLD
? 0xFFFF : 0)) return NULL
;
1388 /* Correct index. Old vehicles were saved differently:
1389 * invalid vehicle was 0xFFFF, now we use 0x0000 for everything invalid. */
1390 if (rt
!= REF_VEHICLE_OLD
) index
--;
1394 if (OrderList::IsValidID(index
)) return OrderList::Get(index
);
1395 SlErrorCorrupt("Referencing invalid OrderList");
1398 if (Order::IsValidID(index
)) return Order::Get(index
);
1399 /* in old versions, invalid order was used to mark end of order list */
1400 if (IsSavegameVersionBefore(5, 2)) return NULL
;
1401 SlErrorCorrupt("Referencing invalid Order");
1403 case REF_VEHICLE_OLD
:
1405 if (Vehicle::IsValidID(index
)) return Vehicle::Get(index
);
1406 SlErrorCorrupt("Referencing invalid Vehicle");
1408 case REF_TEMPLATE_VEHICLE
:
1409 if (TemplateVehicle::IsValidID(index
)) return TemplateVehicle::Get(index
);
1410 SlErrorCorrupt("Referencing invalid TemplateVehicle");
1413 if (Station::IsValidID(index
)) return Station::Get(index
);
1414 SlErrorCorrupt("Referencing invalid Station");
1417 if (Town::IsValidID(index
)) return Town::Get(index
);
1418 SlErrorCorrupt("Referencing invalid Town");
1421 if (RoadStop::IsValidID(index
)) return RoadStop::Get(index
);
1422 SlErrorCorrupt("Referencing invalid RoadStop");
1425 if (Dock::IsValidID(index
)) return Dock::Get(index
);
1426 SlErrorCorrupt("Referencing invalid Dock");
1428 case REF_ENGINE_RENEWS
:
1429 if (EngineRenew::IsValidID(index
)) return EngineRenew::Get(index
);
1430 SlErrorCorrupt("Referencing invalid EngineRenew");
1432 case REF_CARGO_PACKET
:
1433 if (CargoPacket::IsValidID(index
)) return CargoPacket::Get(index
);
1434 SlErrorCorrupt("Referencing invalid CargoPacket");
1437 if (PersistentStorage::IsValidID(index
)) return PersistentStorage::Get(index
);
1438 SlErrorCorrupt("Referencing invalid PersistentStorage");
1440 case REF_LINK_GRAPH
:
1441 if (LinkGraph::IsValidID(index
)) return LinkGraph::Get(index
);
1442 SlErrorCorrupt("Referencing invalid LinkGraph");
1444 case REF_LINK_GRAPH_JOB
:
1445 if (LinkGraphJob::IsValidID(index
)) return LinkGraphJob::Get(index
);
1446 SlErrorCorrupt("Referencing invalid LinkGraphJob");
1448 default: NOT_REACHED();
1453 * Return the size in bytes of a list
1454 * @param list The std::list to find the size of
1456 template<typename PtrList
>
1457 static inline size_t SlCalcListLen(const void *list
)
1459 const PtrList
*l
= (const PtrList
*)list
;
1461 int type_size
= IsSavegameVersionBefore(69) ? 2 : 4;
1462 /* Each entry is saved as type_size bytes, plus type_size bytes are used for the length
1464 return l
->size() * type_size
+ type_size
;
1468 * Return the size in bytes of a list
1469 * @param list The std::list to find the size of
1471 template<typename PtrList
>
1472 static inline size_t SlCalcVarListLen(const void *list
, size_t item_size
)
1474 const PtrList
*l
= (const PtrList
*) list
;
1475 /* Each entry is saved as item_size bytes, plus 4 bytes are used for the length
1477 return l
->size() * item_size
+ 4;
1483 * @param list The list being manipulated
1484 * @param conv SLRefType type of the list (Vehicle *, Station *, etc)
1486 template<typename PtrList
>
1487 static void SlList(void *list
, SLRefType conv
)
1489 /* Automatically calculate the length? */
1490 if (_sl
.need_length
!= NL_NONE
) {
1491 SlSetLength(SlCalcListLen
<PtrList
>(list
));
1492 /* Determine length only? */
1493 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1496 PtrList
*l
= (PtrList
*)list
;
1498 switch (_sl
.action
) {
1500 SlWriteUint32((uint32
)l
->size());
1502 typename
PtrList::iterator iter
;
1503 for (iter
= l
->begin(); iter
!= l
->end(); ++iter
) {
1505 SlWriteUint32((uint32
)ReferenceToInt(ptr
, conv
));
1509 case SLA_LOAD_CHECK
:
1511 size_t length
= IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1513 /* Load each reference and push to the end of the list */
1514 for (size_t i
= 0; i
< length
; i
++) {
1515 size_t data
= IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1516 l
->push_back((void *)data
);
1524 typename
PtrList::iterator iter
;
1525 for (iter
= temp
.begin(); iter
!= temp
.end(); ++iter
) {
1526 void *ptr
= IntToReference((size_t)*iter
, conv
);
1534 default: NOT_REACHED();
1540 * @param list The list being manipulated
1541 * @param conv VarType type of the list
1543 template<typename PtrList
>
1544 static void SlVarList(void *list
, VarType conv
)
1546 const size_t size_len
= SlCalcConvMemLen(conv
);
1547 /* Automatically calculate the length? */
1548 if (_sl
.need_length
!= NL_NONE
) {
1549 SlSetLength(SlCalcVarListLen
<PtrList
>(list
, size_len
));
1550 /* Determine length only? */
1551 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1554 PtrList
*l
= (PtrList
*)list
;
1556 switch (_sl
.action
) {
1558 SlWriteUint32((uint32
)l
->size());
1560 typename
PtrList::iterator iter
;
1561 for (iter
= l
->begin(); iter
!= l
->end(); ++iter
) {
1562 SlSaveLoadConv(&(*iter
), conv
);
1566 case SLA_LOAD_CHECK
:
1568 size_t length
= SlReadUint32();
1571 typename
PtrList::iterator iter
;
1574 for (size_t i
= 0; i
< length
; i
++) {
1575 SlSaveLoadConv(&(*iter
), conv
);
1580 case SLA_PTRS
: break;
1584 default: NOT_REACHED();
1589 /** Are we going to save this object or not? */
1590 static inline bool SlIsObjectValidInSavegame(const SaveLoad
*sld
)
1592 if (_sl_version
< sld
->version_from
|| _sl_version
> sld
->version_to
) return false;
1593 if (sld
->conv
& SLF_NOT_IN_SAVE
) return false;
1599 * Are we going to load this variable when loading a savegame or not?
1600 * @note If the variable is skipped it is skipped in the savegame
1601 * bytestream itself as well, so there is no need to skip it somewhere else
1603 static inline bool SlSkipVariableOnLoad(const SaveLoad
*sld
)
1605 if ((sld
->conv
& SLF_NO_NETWORK_SYNC
) && _sl
.action
!= SLA_SAVE
&& _networking
&& !_network_server
) {
1606 SlSkipBytes(SlCalcConvMemLen(sld
->conv
) * sld
->length
);
1614 * Calculate the size of an object.
1615 * @param object to be measured
1616 * @param sld The SaveLoad description of the object so we know how to manipulate it
1617 * @return size of given object
1619 size_t SlCalcObjLength(const void *object
, const SaveLoad
*sld
)
1623 /* Need to determine the length and write a length tag. */
1624 for (; sld
->cmd
!= SL_END
; sld
++) {
1625 length
+= SlCalcObjMemberLength(object
, sld
);
1630 size_t SlCalcObjMemberLength(const void *object
, const SaveLoad
*sld
)
1632 assert(_sl
.action
== SLA_SAVE
);
1644 /* CONDITIONAL saveload types depend on the savegame version */
1645 if (!SlIsObjectValidInSavegame(sld
)) break;
1648 case SL_VAR
: return SlCalcConvFileLen(sld
->conv
);
1649 case SL_REF
: return SlCalcRefLen();
1650 case SL_ARR
: return SlCalcArrayLen(sld
->length
, sld
->conv
);
1651 case SL_STR
: return SlCalcStringLen(GetVariableAddress(object
, sld
), sld
->length
, sld
->conv
);
1652 case SL_LST
: return SlCalcListLen
<std::list
<void *>>(GetVariableAddress(object
, sld
));
1653 case SL_DEQ
: return SlCalcListLen
<std::deque
<void *>>(GetVariableAddress(object
, sld
));
1654 case SL_VEC
: return SlCalcListLen
<std::vector
<void *>>(GetVariableAddress(object
, sld
));
1656 const size_t size_len
= SlCalcConvMemLen(sld
->conv
);
1658 case 1: return SlCalcVarListLen
<std::vector
<byte
>>(GetVariableAddress(object
, sld
), 1);
1659 case 2: return SlCalcVarListLen
<std::vector
<uint16
>>(GetVariableAddress(object
, sld
), 2);
1660 case 4: return SlCalcVarListLen
<std::vector
<uint32
>>(GetVariableAddress(object
, sld
), 4);
1661 case 8: return SlCalcVarListLen
<std::vector
<uint64
>>(GetVariableAddress(object
, sld
), 8);
1662 default: NOT_REACHED();
1665 case SL_STDSTR
: return SlCalcStdStrLen(*static_cast<std::string
*>(GetVariableAddress(object
, sld
)));
1666 default: NOT_REACHED();
1669 case SL_WRITEBYTE
: return 1; // a byte is logically of size 1
1670 case SL_VEH_INCLUDE
: return SlCalcObjLength(object
, GetVehicleDescription(VEH_END
));
1671 case SL_ST_INCLUDE
: return SlCalcObjLength(object
, GetBaseStationDescription());
1672 default: NOT_REACHED();
1680 * Check whether the variable size of the variable in the saveload configuration
1681 * matches with the actual variable size.
1682 * @param sld The saveload configuration to test.
1684 static bool IsVariableSizeRight(const SaveLoad
*sld
)
1688 switch (GetVarMemType(sld
->conv
)) {
1690 return sld
->size
== sizeof(bool);
1693 return sld
->size
== sizeof(int8
);
1696 return sld
->size
== sizeof(int16
);
1699 return sld
->size
== sizeof(int32
);
1702 return sld
->size
== sizeof(int64
);
1704 return sld
->size
== sizeof(void *);
1707 /* These should all be pointer sized. */
1708 return sld
->size
== sizeof(void *);
1711 /* These should be pointer sized, or fixed array. */
1712 return sld
->size
== sizeof(void *) || sld
->size
== sld
->length
;
1715 return sld
->size
== sizeof(std::string
);
1722 #endif /* OTTD_ASSERT */
1724 bool SlObjectMember(void *ptr
, const SaveLoad
*sld
)
1727 assert(IsVariableSizeRight(sld
));
1730 VarType conv
= GB(sld
->conv
, 0, 8);
1741 /* CONDITIONAL saveload types depend on the savegame version */
1742 if (!SlIsObjectValidInSavegame(sld
)) return false;
1743 if (SlSkipVariableOnLoad(sld
)) return false;
1746 case SL_VAR
: SlSaveLoadConv(ptr
, conv
); break;
1747 case SL_REF
: // Reference variable, translate
1748 switch (_sl
.action
) {
1750 SlWriteUint32((uint32
)ReferenceToInt(*(void **)ptr
, (SLRefType
)conv
));
1752 case SLA_LOAD_CHECK
:
1754 *(size_t *)ptr
= IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1757 *(void **)ptr
= IntToReference(*(size_t *)ptr
, (SLRefType
)conv
);
1760 *(void **)ptr
= NULL
;
1762 default: NOT_REACHED();
1765 case SL_ARR
: SlArray(ptr
, sld
->length
, conv
); break;
1766 case SL_STR
: SlString(ptr
, sld
->length
, sld
->conv
); break;
1767 case SL_LST
: SlList
<std::list
<void *>>(ptr
, (SLRefType
)conv
); break;
1768 case SL_DEQ
: SlList
<std::deque
<void *>>(ptr
, (SLRefType
)conv
); break;
1769 case SL_VEC
: SlList
<std::vector
<void *>>(ptr
, (SLRefType
)conv
); break;
1771 const size_t size_len
= SlCalcConvMemLen(sld
->conv
);
1773 case 1: SlVarList
<std::vector
<byte
>>(ptr
, conv
); break;
1774 case 2: SlVarList
<std::vector
<uint16
>>(ptr
, conv
); break;
1775 case 4: SlVarList
<std::vector
<uint32
>>(ptr
, conv
); break;
1776 case 8: SlVarList
<std::vector
<uint64
>>(ptr
, conv
); break;
1777 default: NOT_REACHED();
1781 case SL_STDSTR
: SlStdString(*static_cast<std::string
*>(ptr
), sld
->conv
); break;
1782 default: NOT_REACHED();
1786 /* SL_WRITEBYTE translates a value of a variable to another one upon
1787 * saving or loading.
1788 * XXX - variable renaming abuse
1789 * game_value: the value of the variable ingame is abused by sld->version_from
1790 * file_value: the value of the variable in the savegame is abused by sld->version_to */
1792 switch (_sl
.action
) {
1793 case SLA_SAVE
: SlWriteByte(sld
->version_to
); break;
1794 case SLA_LOAD_CHECK
:
1795 case SLA_LOAD
: *(byte
*)ptr
= sld
->version_from
; break;
1796 case SLA_PTRS
: break;
1797 case SLA_NULL
: break;
1798 default: NOT_REACHED();
1802 /* SL_VEH_INCLUDE loads common code for vehicles */
1803 case SL_VEH_INCLUDE
:
1804 SlObject(ptr
, GetVehicleDescription(VEH_END
));
1808 SlObject(ptr
, GetBaseStationDescription());
1811 default: NOT_REACHED();
1817 * Main SaveLoad function.
1818 * @param object The object that is being saved or loaded
1819 * @param sld The SaveLoad description of the object so we know how to manipulate it
1821 void SlObject(void *object
, const SaveLoad
*sld
)
1823 /* Automatically calculate the length? */
1824 if (_sl
.need_length
!= NL_NONE
) {
1825 SlSetLength(SlCalcObjLength(object
, sld
));
1826 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1829 for (; sld
->cmd
!= SL_END
; sld
++) {
1830 void *ptr
= sld
->global
? sld
->address
: GetVariableAddress(object
, sld
);
1831 SlObjectMember(ptr
, sld
);
1836 * Save or Load (a list of) global variables
1837 * @param sldg The global variable that is being loaded or saved
1839 void SlGlobList(const SaveLoadGlobVarList
*sldg
)
1841 SlObject(NULL
, (const SaveLoad
*)sldg
);
1845 * Do something of which I have no idea what it is :P
1846 * @param proc The callback procedure that is called
1847 * @param arg The variable that will be used for the callback procedure
1849 void SlAutolength(AutolengthProc
*proc
, void *arg
)
1853 assert(_sl
.action
== SLA_SAVE
);
1855 /* Tell it to calculate the length */
1856 _sl
.need_length
= NL_CALCLENGTH
;
1861 _sl
.need_length
= NL_WANTLENGTH
;
1862 SlSetLength(_sl
.obj_len
);
1864 offs
= _sl
.dumper
->GetSize() + _sl
.obj_len
;
1866 /* And write the stuff */
1869 if (offs
!= _sl
.dumper
->GetSize()) SlErrorCorrupt("Invalid chunk size");
1873 * Load a chunk of data (eg vehicles, stations, etc.)
1874 * @param ch The chunkhandler that will be used for the operation
1876 static void SlLoadChunk(const ChunkHandler
*ch
)
1878 byte m
= SlReadByte();
1887 _sl
.array_index
= 0;
1889 if (_next_offs
!= 0) SlErrorCorrupt("Invalid array length");
1891 case CH_SPARSE_ARRAY
:
1893 if (_next_offs
!= 0) SlErrorCorrupt("Invalid array length");
1896 if ((m
& 0xF) == CH_RIFF
) {
1898 len
= (SlReadByte() << 16) | ((m
>> 4) << 24);
1899 len
+= SlReadUint16();
1901 endoffs
= _sl
.reader
->GetSize() + len
;
1903 if (_sl
.reader
->GetSize() != endoffs
) SlErrorCorrupt("Invalid chunk size");
1905 SlErrorCorrupt("Invalid chunk type");
1912 * Load a chunk of data for checking savegames.
1913 * If the chunkhandler is NULL, the chunk is skipped.
1914 * @param ch The chunkhandler that will be used for the operation
1916 static void SlLoadCheckChunk(const ChunkHandler
*ch
)
1918 byte m
= SlReadByte();
1927 _sl
.array_index
= 0;
1928 if (ch
->load_check_proc
) {
1929 ch
->load_check_proc();
1934 case CH_SPARSE_ARRAY
:
1935 if (ch
->load_check_proc
) {
1936 ch
->load_check_proc();
1942 if ((m
& 0xF) == CH_RIFF
) {
1944 len
= (SlReadByte() << 16) | ((m
>> 4) << 24);
1945 len
+= SlReadUint16();
1947 endoffs
= _sl
.reader
->GetSize() + len
;
1948 if (ch
->load_check_proc
) {
1949 ch
->load_check_proc();
1953 if (_sl
.reader
->GetSize() != endoffs
) SlErrorCorrupt("Invalid chunk size");
1955 SlErrorCorrupt("Invalid chunk type");
1962 * Save a chunk of data (eg. vehicles, stations, etc.). Each chunk is
1963 * prefixed by an ID identifying it, followed by data, and terminator where appropriate
1964 * @param ch The chunkhandler that will be used for the operation
1966 static void SlSaveChunk(const ChunkHandler
*ch
)
1968 ChunkSaveLoadProc
*proc
= ch
->save_proc
;
1970 /* Don't save any chunk information if there is no save handler. */
1971 if (proc
== NULL
) return;
1973 SlWriteUint32(ch
->id
);
1974 DEBUG(sl
, 2, "Saving chunk %c%c%c%c", ch
->id
>> 24, ch
->id
>> 16, ch
->id
>> 8, ch
->id
);
1976 _sl
.block_mode
= ch
->flags
& CH_TYPE_MASK
;
1977 switch (ch
->flags
& CH_TYPE_MASK
) {
1979 _sl
.need_length
= NL_WANTLENGTH
;
1983 _sl
.last_array_index
= 0;
1984 SlWriteByte(CH_ARRAY
);
1986 SlWriteArrayLength(0); // Terminate arrays
1988 case CH_SPARSE_ARRAY
:
1989 SlWriteByte(CH_SPARSE_ARRAY
);
1991 SlWriteArrayLength(0); // Terminate arrays
1993 default: NOT_REACHED();
1997 /** Save all chunks */
1998 static void SlSaveChunks()
2000 FOR_ALL_CHUNK_HANDLERS(ch
) {
2009 * Find the ChunkHandler that will be used for processing the found
2010 * chunk in the savegame or in memory
2011 * @param id the chunk in question
2012 * @return returns the appropriate chunkhandler
2014 static const ChunkHandler
*SlFindChunkHandler(uint32 id
)
2016 FOR_ALL_CHUNK_HANDLERS(ch
) if (ch
->id
== id
) return ch
;
2020 /** Load all chunks */
2021 static void SlLoadChunks()
2024 const ChunkHandler
*ch
;
2026 for (id
= SlReadUint32(); id
!= 0; id
= SlReadUint32()) {
2027 DEBUG(sl
, 2, "Loading chunk %c%c%c%c", id
>> 24, id
>> 16, id
>> 8, id
);
2029 ch
= SlFindChunkHandler(id
);
2030 if (ch
== NULL
) SlErrorCorrupt("Unknown chunk type");
2035 /** Load all chunks for savegame checking */
2036 static void SlLoadCheckChunks()
2039 const ChunkHandler
*ch
;
2041 for (id
= SlReadUint32(); id
!= 0; id
= SlReadUint32()) {
2042 DEBUG(sl
, 2, "Loading chunk %c%c%c%c", id
>> 24, id
>> 16, id
>> 8, id
);
2044 ch
= SlFindChunkHandler(id
);
2045 if (ch
== NULL
) SlErrorCorrupt("Unknown chunk type");
2046 SlLoadCheckChunk(ch
);
2050 /** Fix all pointers (convert index -> pointer) */
2051 static void SlFixPointers()
2053 _sl
.action
= SLA_PTRS
;
2055 DEBUG(sl
, 1, "Fixing pointers");
2057 FOR_ALL_CHUNK_HANDLERS(ch
) {
2058 if (ch
->ptrs_proc
!= NULL
) {
2059 DEBUG(sl
, 2, "Fixing pointers for %c%c%c%c", ch
->id
>> 24, ch
->id
>> 16, ch
->id
>> 8, ch
->id
);
2064 DEBUG(sl
, 1, "All pointers fixed");
2066 assert(_sl
.action
== SLA_PTRS
);
2070 /** Yes, simply reading from a file. */
2071 struct FileReader
: LoadFilter
{
2072 FILE *file
; ///< The file to read from.
2073 long begin
; ///< The begin of the file.
2076 * Create the file reader, so it reads from a specific file.
2077 * @param file The file to read from.
2079 FileReader(FILE *file
) : LoadFilter(NULL
), file(file
), begin(ftell(file
))
2083 /** Make sure everything is cleaned up. */
2086 if (this->file
!= NULL
) fclose(this->file
);
2089 /* Make sure we don't double free. */
2093 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2095 /* We're in the process of shutting down, i.e. in "failure" mode. */
2096 if (this->file
== NULL
) return 0;
2098 return fread(buf
, 1, size
, this->file
);
2101 /* virtual */ void Reset()
2103 clearerr(this->file
);
2104 if (fseek(this->file
, this->begin
, SEEK_SET
)) {
2105 DEBUG(sl
, 1, "Could not reset the file reading");
2110 /** Yes, simply writing to a file. */
2111 struct FileWriter
: SaveFilter
{
2112 FILE *file
; ///< The file to write to.
2115 * Create the file writer, so it writes to a specific file.
2116 * @param file The file to write to.
2118 FileWriter(FILE *file
) : SaveFilter(NULL
), file(file
)
2122 /** Make sure everything is cleaned up. */
2127 /* Make sure we don't double free. */
2131 /* virtual */ void Write(byte
*buf
, size_t size
)
2133 /* We're in the process of shutting down, i.e. in "failure" mode. */
2134 if (this->file
== NULL
) return;
2136 if (fwrite(buf
, 1, size
, this->file
) != size
) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE
);
2139 /* virtual */ void Finish()
2141 if (this->file
!= NULL
) fclose(this->file
);
2146 /*******************************************
2147 ********** START OF LZO CODE **************
2148 *******************************************/
2151 #include <lzo/lzo1x.h>
2153 /** Buffer size for the LZO compressor */
2154 static const uint LZO_BUFFER_SIZE
= 8192;
2156 /** Filter using LZO compression. */
2157 struct LZOLoadFilter
: LoadFilter
{
2159 * Initialise this filter.
2160 * @param chain The next filter in this chain.
2162 LZOLoadFilter(LoadFilter
*chain
) : LoadFilter(chain
)
2164 if (lzo_init() != LZO_E_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize decompressor");
2167 /* virtual */ size_t Read(byte
*buf
, size_t ssize
)
2169 assert(ssize
>= LZO_BUFFER_SIZE
);
2171 /* Buffer size is from the LZO docs plus the chunk header size. */
2172 byte out
[LZO_BUFFER_SIZE
+ LZO_BUFFER_SIZE
/ 16 + 64 + 3 + sizeof(uint32
) * 2];
2175 lzo_uint len
= ssize
;
2178 if (this->chain
->Read((byte
*)tmp
, sizeof(tmp
)) != sizeof(tmp
)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
, "File read failed");
2180 /* Check if size is bad */
2181 ((uint32
*)out
)[0] = size
= tmp
[1];
2183 if (_sl_version
!= 0) {
2184 tmp
[0] = TO_BE32(tmp
[0]);
2185 size
= TO_BE32(size
);
2188 if (size
>= sizeof(out
)) SlErrorCorrupt("Inconsistent size");
2191 if (this->chain
->Read(out
+ sizeof(uint32
), size
) != size
) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
2193 /* Verify checksum */
2194 if (tmp
[0] != lzo_adler32(0, out
, size
+ sizeof(uint32
))) SlErrorCorrupt("Bad checksum");
2197 int ret
= lzo1x_decompress_safe(out
+ sizeof(uint32
) * 1, size
, buf
, &len
, NULL
);
2198 if (ret
!= LZO_E_OK
) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
2203 /** Filter using LZO compression. */
2204 struct LZOSaveFilter
: SaveFilter
{
2206 * Initialise this filter.
2207 * @param chain The next filter in this chain.
2208 * @param compression_level The requested level of compression.
2210 LZOSaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
)
2212 if (lzo_init() != LZO_E_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize compressor");
2215 /* virtual */ void Write(byte
*buf
, size_t size
)
2217 const lzo_bytep in
= buf
;
2218 /* Buffer size is from the LZO docs plus the chunk header size. */
2219 byte out
[LZO_BUFFER_SIZE
+ LZO_BUFFER_SIZE
/ 16 + 64 + 3 + sizeof(uint32
) * 2];
2220 byte wrkmem
[LZO1X_1_MEM_COMPRESS
];
2224 /* Compress up to LZO_BUFFER_SIZE bytes at once. */
2225 lzo_uint len
= size
> LZO_BUFFER_SIZE
? LZO_BUFFER_SIZE
: (lzo_uint
)size
;
2226 lzo1x_1_compress(in
, len
, out
+ sizeof(uint32
) * 2, &outlen
, wrkmem
);
2227 ((uint32
*)out
)[1] = TO_BE32((uint32
)outlen
);
2228 ((uint32
*)out
)[0] = TO_BE32(lzo_adler32(0, out
+ sizeof(uint32
), outlen
+ sizeof(uint32
)));
2229 this->chain
->Write(out
, outlen
+ sizeof(uint32
) * 2);
2231 /* Move to next data chunk. */
2238 #endif /* WITH_LZO */
2240 /*********************************************
2241 ******** START OF NOCOMP CODE (uncompressed)*
2242 *********************************************/
2244 /** Filter without any compression. */
2245 struct NoCompLoadFilter
: LoadFilter
{
2247 * Initialise this filter.
2248 * @param chain The next filter in this chain.
2250 NoCompLoadFilter(LoadFilter
*chain
) : LoadFilter(chain
)
2254 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2256 return this->chain
->Read(buf
, size
);
2260 /** Filter without any compression. */
2261 struct NoCompSaveFilter
: SaveFilter
{
2263 * Initialise this filter.
2264 * @param chain The next filter in this chain.
2265 * @param compression_level The requested level of compression.
2267 NoCompSaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
)
2271 /* virtual */ void Write(byte
*buf
, size_t size
)
2273 this->chain
->Write(buf
, size
);
2277 /********************************************
2278 ********** START OF ZLIB CODE **************
2279 ********************************************/
2281 #if defined(WITH_ZLIB)
2284 /** Filter using Zlib compression. */
2285 struct ZlibLoadFilter
: LoadFilter
{
2286 z_stream z
; ///< Stream state we are reading from.
2287 byte fread_buf
[MEMORY_CHUNK_SIZE
]; ///< Buffer for reading from the file.
2290 * Initialise this filter.
2291 * @param chain The next filter in this chain.
2293 ZlibLoadFilter(LoadFilter
*chain
) : LoadFilter(chain
)
2295 memset(&this->z
, 0, sizeof(this->z
));
2296 if (inflateInit(&this->z
) != Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize decompressor");
2299 /** Clean everything up. */
2302 inflateEnd(&this->z
);
2305 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2307 this->z
.next_out
= buf
;
2308 this->z
.avail_out
= (uint
)size
;
2311 /* read more bytes from the file? */
2312 if (this->z
.avail_in
== 0) {
2313 this->z
.next_in
= this->fread_buf
;
2314 this->z
.avail_in
= (uint
)this->chain
->Read(this->fread_buf
, sizeof(this->fread_buf
));
2317 /* inflate the data */
2318 int r
= inflate(&this->z
, 0);
2319 if (r
== Z_STREAM_END
) break;
2321 if (r
!= Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "inflate() failed");
2322 } while (this->z
.avail_out
!= 0);
2324 return size
- this->z
.avail_out
;
2328 /** Filter using Zlib compression. */
2329 struct ZlibSaveFilter
: SaveFilter
{
2330 z_stream z
; ///< Stream state we are writing to.
2333 * Initialise this filter.
2334 * @param chain The next filter in this chain.
2335 * @param compression_level The requested level of compression.
2337 ZlibSaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
)
2339 memset(&this->z
, 0, sizeof(this->z
));
2340 if (deflateInit(&this->z
, compression_level
) != Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize compressor");
2343 /** Clean up what we allocated. */
2346 deflateEnd(&this->z
);
2350 * Helper loop for writing the data.
2351 * @param p The bytes to write.
2352 * @param len Amount of bytes to write.
2353 * @param mode Mode for deflate.
2355 void WriteLoop(byte
*p
, size_t len
, int mode
)
2357 byte buf
[MEMORY_CHUNK_SIZE
]; // output buffer
2359 this->z
.next_in
= p
;
2360 this->z
.avail_in
= (uInt
)len
;
2362 this->z
.next_out
= buf
;
2363 this->z
.avail_out
= sizeof(buf
);
2366 * For the poor next soul who sees many valgrind warnings of the
2367 * "Conditional jump or move depends on uninitialised value(s)" kind:
2368 * According to the author of zlib it is not a bug and it won't be fixed.
2369 * http://groups.google.com/group/comp.compression/browse_thread/thread/b154b8def8c2a3ef/cdf9b8729ce17ee2
2370 * [Mark Adler, Feb 24 2004, 'zlib-1.2.1 valgrind warnings' in the newsgroup comp.compression]
2372 int r
= deflate(&this->z
, mode
);
2374 /* bytes were emitted? */
2375 if ((n
= sizeof(buf
) - this->z
.avail_out
) != 0) {
2376 this->chain
->Write(buf
, n
);
2378 if (r
== Z_STREAM_END
) break;
2380 if (r
!= Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "zlib returned error code");
2381 } while (this->z
.avail_in
|| !this->z
.avail_out
);
2384 /* virtual */ void Write(byte
*buf
, size_t size
)
2386 this->WriteLoop(buf
, size
, 0);
2389 /* virtual */ void Finish()
2391 this->WriteLoop(NULL
, 0, Z_FINISH
);
2392 this->chain
->Finish();
2396 #endif /* WITH_ZLIB */
2398 /********************************************
2399 ********** START OF LZMA CODE **************
2400 ********************************************/
2402 #if defined(WITH_LZMA)
2406 * Have a copy of an initialised LZMA stream. We need this as it's
2407 * impossible to "re"-assign LZMA_STREAM_INIT to a variable in some
2408 * compilers, i.e. LZMA_STREAM_INIT can't be used to set something.
2409 * This var has to be used instead.
2411 static const lzma_stream _lzma_init
= LZMA_STREAM_INIT
;
2413 /** Filter without any compression. */
2414 struct LZMALoadFilter
: LoadFilter
{
2415 lzma_stream lzma
; ///< Stream state that we are reading from.
2416 byte fread_buf
[MEMORY_CHUNK_SIZE
]; ///< Buffer for reading from the file.
2419 * Initialise this filter.
2420 * @param chain The next filter in this chain.
2422 LZMALoadFilter(LoadFilter
*chain
) : LoadFilter(chain
), lzma(_lzma_init
)
2424 /* Allow saves up to 256 MB uncompressed */
2425 if (lzma_auto_decoder(&this->lzma
, 1 << 28, 0) != LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize decompressor");
2428 /** Clean everything up. */
2431 lzma_end(&this->lzma
);
2434 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2436 this->lzma
.next_out
= buf
;
2437 this->lzma
.avail_out
= size
;
2440 /* read more bytes from the file? */
2441 if (this->lzma
.avail_in
== 0) {
2442 this->lzma
.next_in
= this->fread_buf
;
2443 this->lzma
.avail_in
= this->chain
->Read(this->fread_buf
, sizeof(this->fread_buf
));
2446 /* inflate the data */
2447 lzma_ret r
= lzma_code(&this->lzma
, LZMA_RUN
);
2448 if (r
== LZMA_STREAM_END
) break;
2449 if (r
!= LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "liblzma returned error code");
2450 } while (this->lzma
.avail_out
!= 0);
2452 return size
- this->lzma
.avail_out
;
2456 /** Filter using LZMA compression. */
2457 struct LZMASaveFilter
: SaveFilter
{
2458 lzma_stream lzma
; ///< Stream state that we are writing to.
2461 * Initialise this filter.
2462 * @param chain The next filter in this chain.
2463 * @param compression_level The requested level of compression.
2465 LZMASaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
), lzma(_lzma_init
)
2467 if (lzma_easy_encoder(&this->lzma
, compression_level
, LZMA_CHECK_CRC32
) != LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize compressor");
2470 /** Clean up what we allocated. */
2473 lzma_end(&this->lzma
);
2477 * Helper loop for writing the data.
2478 * @param p The bytes to write.
2479 * @param len Amount of bytes to write.
2480 * @param action Action for lzma_code.
2482 void WriteLoop(byte
*p
, size_t len
, lzma_action action
)
2484 byte buf
[MEMORY_CHUNK_SIZE
]; // output buffer
2486 this->lzma
.next_in
= p
;
2487 this->lzma
.avail_in
= len
;
2489 this->lzma
.next_out
= buf
;
2490 this->lzma
.avail_out
= sizeof(buf
);
2492 lzma_ret r
= lzma_code(&this->lzma
, action
);
2494 /* bytes were emitted? */
2495 if ((n
= sizeof(buf
) - this->lzma
.avail_out
) != 0) {
2496 this->chain
->Write(buf
, n
);
2498 if (r
== LZMA_STREAM_END
) break;
2499 if (r
!= LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "liblzma returned error code");
2500 } while (this->lzma
.avail_in
|| !this->lzma
.avail_out
);
2503 /* virtual */ void Write(byte
*buf
, size_t size
)
2505 this->WriteLoop(buf
, size
, LZMA_RUN
);
2508 /* virtual */ void Finish()
2510 this->WriteLoop(NULL
, 0, LZMA_FINISH
);
2511 this->chain
->Finish();
2515 #endif /* WITH_LZMA */
2517 /*******************************************
2518 ************* END OF CODE *****************
2519 *******************************************/
2521 /** The format for a reader/writer type of a savegame */
2522 struct SaveLoadFormat
{
2523 const char *name
; ///< name of the compressor/decompressor (debug-only)
2524 uint32 tag
; ///< the 4-letter tag by which it is identified in the savegame
2526 LoadFilter
*(*init_load
)(LoadFilter
*chain
); ///< Constructor for the load filter.
2527 SaveFilter
*(*init_write
)(SaveFilter
*chain
, byte compression
); ///< Constructor for the save filter.
2529 byte min_compression
; ///< the minimum compression level of this format
2530 byte default_compression
; ///< the default compression level of this format
2531 byte max_compression
; ///< the maximum compression level of this format
2534 /** The different saveload formats known/understood by OpenTTD. */
2535 static const SaveLoadFormat _saveload_formats
[] = {
2536 #if defined(WITH_LZO)
2537 /* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
2538 {"lzo", TO_BE32X('OTTD'), CreateLoadFilter
<LZOLoadFilter
>, CreateSaveFilter
<LZOSaveFilter
>, 0, 0, 0},
2540 {"lzo", TO_BE32X('OTTD'), NULL
, NULL
, 0, 0, 0},
2542 /* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
2543 {"none", TO_BE32X('OTTN'), CreateLoadFilter
<NoCompLoadFilter
>, CreateSaveFilter
<NoCompSaveFilter
>, 0, 0, 0},
2544 #if defined(WITH_ZLIB)
2545 /* After level 6 the speed reduction is significant (1.5x to 2.5x slower per level), but the reduction in filesize is
2546 * fairly insignificant (~1% for each step). Lower levels become ~5-10% bigger by each level than level 6 while level
2547 * 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
2548 {"zlib", TO_BE32X('OTTZ'), CreateLoadFilter
<ZlibLoadFilter
>, CreateSaveFilter
<ZlibSaveFilter
>, 0, 6, 9},
2550 {"zlib", TO_BE32X('OTTZ'), NULL
, NULL
, 0, 0, 0},
2552 #if defined(WITH_LZMA)
2553 /* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
2554 * Higher compression levels are possible, and might improve savegame size by up to 25%, but are also up to 10 times slower.
2555 * The next significant reduction in file size is at level 4, but that is already 4 times slower. Level 3 is primarily 50%
2556 * slower while not improving the filesize, while level 0 and 1 are faster, but don't reduce savegame size much.
2557 * It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
2558 {"lzma", TO_BE32X('OTTX'), CreateLoadFilter
<LZMALoadFilter
>, CreateSaveFilter
<LZMASaveFilter
>, 0, 2, 9},
2560 {"lzma", TO_BE32X('OTTX'), NULL
, NULL
, 0, 0, 0},
2565 * Return the savegameformat of the game. Whether it was created with ZLIB compression
2566 * uncompressed, or another type
2567 * @param s Name of the savegame format. If NULL it picks the first available one
2568 * @param compression_level Output for telling what compression level we want.
2569 * @return Pointer to SaveLoadFormat struct giving all characteristics of this type of savegame
2571 static const SaveLoadFormat
*GetSavegameFormat(char *s
, byte
*compression_level
)
2573 const SaveLoadFormat
*def
= lastof(_saveload_formats
);
2575 /* find default savegame format, the highest one with which files can be written */
2576 while (!def
->init_write
) def
--;
2579 /* Get the ":..." of the compression level out of the way */
2580 char *complevel
= strrchr(s
, ':');
2581 if (complevel
!= NULL
) *complevel
= '\0';
2583 for (const SaveLoadFormat
*slf
= &_saveload_formats
[0]; slf
!= endof(_saveload_formats
); slf
++) {
2584 if (slf
->init_write
!= NULL
&& strcmp(s
, slf
->name
) == 0) {
2585 *compression_level
= slf
->default_compression
;
2586 if (complevel
!= NULL
) {
2587 /* There is a compression level in the string.
2588 * First restore the : we removed to do proper name matching,
2589 * then move the the begin of the actual version. */
2593 /* Get the version and determine whether all went fine. */
2595 long level
= strtol(complevel
, &end
, 10);
2596 if (end
== complevel
|| level
!= Clamp(level
, slf
->min_compression
, slf
->max_compression
)) {
2597 SetDParamStr(0, complevel
);
2598 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_LEVEL
, WL_CRITICAL
);
2600 *compression_level
= level
;
2608 SetDParamStr(1, def
->name
);
2609 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM
, WL_CRITICAL
);
2611 /* Restore the string by adding the : back */
2612 if (complevel
!= NULL
) *complevel
= ':';
2614 *compression_level
= def
->default_compression
;
2618 /* actual loader/saver function */
2619 void InitializeGame(uint size_x
, uint size_y
, bool reset_date
, bool reset_settings
);
2620 extern bool AfterLoadGame();
2621 extern bool LoadOldSaveGame(const char *file
);
2624 * Clear/free saveload state.
2626 static inline void ClearSaveLoadState()
2642 * Update the gui accordingly when starting saving
2643 * and set locks on saveload. Also turn off fast-forward cause with that
2644 * saving takes Aaaaages
2646 static void SaveFileStart()
2648 _sl
.ff_state
= _fast_forward
;
2650 SetMouseCursorBusy(true);
2652 InvalidateWindowData(WC_STATUS_BAR
, 0, SBI_SAVELOAD_START
);
2653 _sl
.saveinprogress
= true;
2656 /** Update the gui accordingly when saving is done and release locks on saveload. */
2657 static void SaveFileDone()
2659 if (_game_mode
!= GM_MENU
) _fast_forward
= _sl
.ff_state
;
2660 SetMouseCursorBusy(false);
2662 InvalidateWindowData(WC_STATUS_BAR
, 0, SBI_SAVELOAD_FINISH
);
2663 _sl
.saveinprogress
= false;
2666 /** Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friends) */
2667 void SetSaveLoadError(StringID str
)
2669 _sl
.error_str
= str
;
2672 /** Get the string representation of the error message */
2673 const char *GetSaveLoadErrorString()
2675 SetDParam(0, _sl
.error_str
);
2676 SetDParamStr(1, _sl
.extra_msg
);
2678 static char err_str
[512];
2679 GetString(err_str
, _sl
.action
== SLA_SAVE
? STR_ERROR_GAME_SAVE_FAILED
: STR_ERROR_GAME_LOAD_FAILED
, lastof(err_str
));
2683 /** Show a gui message when saving has failed */
2684 static void SaveFileError()
2686 SetDParamStr(0, GetSaveLoadErrorString());
2687 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
2692 * We have written the whole game into memory, _memory_savegame, now find
2693 * and appropriate compressor and start writing to file.
2695 static SaveOrLoadResult
SaveFileToDisk(bool threaded
)
2699 const SaveLoadFormat
*fmt
= GetSavegameFormat(_savegame_format
, &compression
);
2701 /* We have written our stuff to memory, now write it to file! */
2702 uint32 hdr
[2] = { fmt
->tag
, TO_BE32(SAVEGAME_VERSION
<< 16) };
2703 _sl
.sf
->Write((byte
*)hdr
, sizeof(hdr
));
2705 _sl
.sf
= fmt
->init_write(_sl
.sf
, compression
);
2706 _sl
.dumper
->Flush(_sl
.sf
);
2708 ClearSaveLoadState();
2710 if (threaded
) SetAsyncSaveFinish(SaveFileDone
);
2714 ClearSaveLoadState();
2716 AsyncSaveFinishProc asfp
= SaveFileDone
;
2718 /* We don't want to shout when saving is just
2719 * cancelled due to a client disconnecting. */
2720 if (_sl
.error_str
!= STR_NETWORK_ERROR_LOSTCONNECTION
) {
2721 /* Skip the "colour" character */
2722 DEBUG(sl
, 0, "%s", GetSaveLoadErrorString() + 3);
2723 asfp
= SaveFileError
;
2727 SetAsyncSaveFinish(asfp
);
2735 /** Thread run function for saving the file to disk. */
2736 static void SaveFileToDiskThread(void *arg
)
2738 SaveFileToDisk(true);
2741 void WaitTillSaved()
2743 if (_save_thread
== NULL
) return;
2745 _save_thread
->Join();
2746 delete _save_thread
;
2747 _save_thread
= NULL
;
2749 /* Make sure every other state is handled properly as well. */
2750 ProcessAsyncSaveFinish();
2754 * Actually perform the saving of the savegame.
2755 * General tactics is to first save the game to memory, then write it to file
2756 * using the writer, either in threaded mode if possible, or single-threaded.
2757 * @param writer The filter to write the savegame to.
2758 * @param threaded Whether to try to perform the saving asynchronously.
2759 * @return Return the result of the action. #SL_OK or #SL_ERROR
2761 static SaveOrLoadResult
DoSave(SaveFilter
*writer
, bool threaded
)
2763 assert(!_sl
.saveinprogress
);
2765 _sl
.dumper
= new MemoryDumper();
2768 _sl_version
= SAVEGAME_VERSION
;
2770 SaveViewportBeforeSaveGame();
2774 if (!threaded
|| !ThreadObject::New(&SaveFileToDiskThread
, NULL
, &_save_thread
, "ottd:savegame")) {
2775 if (threaded
) DEBUG(sl
, 1, "Cannot create savegame thread, reverting to single-threaded mode...");
2777 SaveOrLoadResult result
= SaveFileToDisk(false);
2787 * Save the game using a (writer) filter.
2788 * @param writer The filter to write the savegame to.
2789 * @param threaded Whether to try to perform the saving asynchronously.
2790 * @return Return the result of the action. #SL_OK or #SL_ERROR
2792 SaveOrLoadResult
SaveWithFilter(SaveFilter
*writer
, bool threaded
)
2795 _sl
.action
= SLA_SAVE
;
2796 return DoSave(writer
, threaded
);
2798 ClearSaveLoadState();
2804 * Actually perform the loading of a "non-old" savegame.
2805 * @param reader The filter to read the savegame from.
2806 * @param load_check Whether to perform the checking ("preview") or actually load the game.
2807 * @return Return the result of the action. #SL_OK or #SL_REINIT ("unload" the game)
2809 static SaveOrLoadResult
DoLoad(LoadFilter
*reader
, bool load_check
)
2814 /* Clear previous check data */
2815 _load_check_data
.Clear();
2816 /* Mark SL_LOAD_CHECK as supported for this savegame. */
2817 _load_check_data
.checkable
= true;
2821 if (_sl
.lf
->Read((byte
*)hdr
, sizeof(hdr
)) != sizeof(hdr
)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
2823 /* see if we have any loader for this type. */
2824 const SaveLoadFormat
*fmt
= _saveload_formats
;
2826 /* No loader found, treat as version 0 and use LZO format */
2827 if (fmt
== endof(_saveload_formats
)) {
2828 DEBUG(sl
, 0, "Unknown savegame type, trying to load it as the buggy format");
2831 _sl_minor_version
= 0;
2833 /* Try to find the LZO savegame format; it uses 'OTTD' as tag. */
2834 fmt
= _saveload_formats
;
2836 if (fmt
== endof(_saveload_formats
)) {
2837 /* Who removed LZO support? Bad bad boy! */
2840 if (fmt
->tag
== TO_BE32X('OTTD')) break;
2846 if (fmt
->tag
== hdr
[0]) {
2847 /* check version number */
2848 _sl_version
= TO_BE32(hdr
[1]) >> 16;
2849 /* Minor is not used anymore from version 18.0, but it is still needed
2850 * in versions before that (4 cases) which can't be removed easy.
2851 * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */
2852 _sl_minor_version
= (TO_BE32(hdr
[1]) >> 8) & 0xFF;
2854 DEBUG(sl
, 1, "Loading savegame version %d", _sl_version
);
2856 /* Is the version higher than the current? */
2857 if (_sl_version
> SAVEGAME_VERSION
) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME
);
2864 /* loader for this savegame type is not implemented? */
2865 if (fmt
->init_load
== NULL
) {
2867 seprintf(err_str
, lastof(err_str
), "Loader for '%s' is not available.", fmt
->name
);
2868 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, err_str
);
2871 _sl
.lf
= fmt
->init_load(_sl
.lf
);
2872 _sl
.reader
= new ReadBuffer(_sl
.lf
);
2876 /* Old maps were hardcoded to 256x256 and thus did not contain
2877 * any mapsize information. Pre-initialize to 256x256 to not to
2878 * confuse old games */
2879 InitializeGame(256, 256, true, true);
2883 if (IsSavegameVersionBefore(4)) {
2885 * NewGRFs were introduced between 0.3,4 and 0.3.5, which both
2886 * shared savegame version 4. Anything before that 'obviously'
2887 * does not have any NewGRFs. Between the introduction and
2888 * savegame version 41 (just before 0.5) the NewGRF settings
2889 * were not stored in the savegame and they were loaded by
2890 * using the settings from the main menu.
2892 * - savegame version < 4: do not load any NewGRFs.
2893 * - savegame version >= 41: load NewGRFs from savegame, which is
2894 * already done at this stage by
2895 * overwriting the main menu settings.
2896 * - other savegame versions: use main menu settings.
2898 * This means that users *can* crash savegame version 4..40
2899 * savegames if they set incompatible NewGRFs in the main menu,
2900 * but can't crash anymore for savegame version < 4 savegames.
2902 * Note: this is done here because AfterLoadGame is also called
2903 * for TTO/TTD/TTDP savegames which have their own NewGRF logic.
2905 ClearGRFConfigList(&_grfconfig
);
2910 /* Load chunks into _load_check_data.
2911 * No pools are loaded. References are not possible, and thus do not need resolving. */
2912 SlLoadCheckChunks();
2914 /* Load chunks and resolve references */
2919 ClearSaveLoadState();
2921 _savegame_type
= SGT_OTTD
;
2924 /* The only part from AfterLoadGame() we need */
2925 _load_check_data
.grf_compatibility
= IsGoodGRFConfigList(_load_check_data
.grfconfig
);
2927 GamelogStartAction(GLAT_LOAD
);
2929 /* After loading fix up savegame for any internal changes that
2930 * might have occurred since then. If it fails, load back the old game. */
2931 if (!AfterLoadGame()) {
2932 GamelogStopAction();
2936 GamelogStopAction();
2943 * Load the game using a (reader) filter.
2944 * @param reader The filter to read the savegame from.
2945 * @return Return the result of the action. #SL_OK or #SL_REINIT ("unload" the game)
2947 SaveOrLoadResult
LoadWithFilter(LoadFilter
*reader
)
2950 _sl
.action
= SLA_LOAD
;
2951 return DoLoad(reader
, false);
2953 ClearSaveLoadState();
2959 * Main Save or Load function where the high-level saveload functions are
2960 * handled. It opens the savegame, selects format and checks versions
2961 * @param filename The name of the savegame being created/loaded
2962 * @param mode Save or load mode. Load can also be a TTD(Patch) game. Use #SL_LOAD, #SL_OLD_LOAD, #SL_LOAD_CHECK, or #SL_SAVE.
2963 * @param sb The sub directory to save the savegame in
2964 * @param threaded True when threaded saving is allowed
2965 * @return Return the result of the action. #SL_OK, #SL_ERROR, or #SL_REINIT ("unload" the game)
2967 SaveOrLoadResult
SaveOrLoad(const char *filename
, SaveLoadOperation fop
, DetailedFileType dft
, Subdirectory sb
, bool threaded
)
2969 /* An instance of saving is already active, so don't go saving again */
2970 if (_sl
.saveinprogress
&& fop
== SLO_SAVE
&& dft
== DFT_GAME_FILE
&& threaded
) {
2971 /* if not an autosave, but a user action, show error message */
2972 if (!_do_autosave
) ShowErrorMessage(STR_ERROR_SAVE_STILL_IN_PROGRESS
, INVALID_STRING_ID
, WL_ERROR
);
2978 /* Load a TTDLX or TTDPatch game */
2979 if (fop
== SLO_LOAD
&& dft
== DFT_OLD_GAME_FILE
) {
2980 InitializeGame(256, 256, true, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
2982 /* TTD/TTO savegames have no NewGRFs, TTDP savegame have them
2983 * and if so a new NewGRF list will be made in LoadOldSaveGame.
2984 * Note: this is done here because AfterLoadGame is also called
2985 * for OTTD savegames which have their own NewGRF logic. */
2986 ClearGRFConfigList(&_grfconfig
);
2988 if (!LoadOldSaveGame(filename
)) return SL_REINIT
;
2990 _sl_minor_version
= 0;
2991 GamelogStartAction(GLAT_LOAD
);
2992 if (!AfterLoadGame()) {
2993 GamelogStopAction();
2996 GamelogStopAction();
3000 assert(dft
== DFT_GAME_FILE
);
3003 _sl
.action
= SLA_LOAD_CHECK
;
3007 _sl
.action
= SLA_LOAD
;
3011 _sl
.action
= SLA_SAVE
;
3014 default: NOT_REACHED();
3017 FILE *fh
= (fop
== SLO_SAVE
) ? FioFOpenFile(filename
, "wb", sb
) : FioFOpenFile(filename
, "rb", sb
);
3019 /* Make it a little easier to load savegames from the console */
3020 if (fh
== NULL
&& fop
!= SLO_SAVE
) fh
= FioFOpenFile(filename
, "rb", SAVE_DIR
);
3021 if (fh
== NULL
&& fop
!= SLO_SAVE
) fh
= FioFOpenFile(filename
, "rb", BASE_DIR
);
3022 if (fh
== NULL
&& fop
!= SLO_SAVE
) fh
= FioFOpenFile(filename
, "rb", SCENARIO_DIR
);
3025 SlError(fop
== SLO_SAVE
? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE
: STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
3028 if (fop
== SLO_SAVE
) { // SAVE game
3029 DEBUG(desync
, 1, "save: %08x; %02x; %s", _date
, _date_fract
, filename
);
3030 if (_network_server
|| !_settings_client
.gui
.threaded_saves
) threaded
= false;
3032 return DoSave(new FileWriter(fh
), threaded
);
3036 assert(fop
== SLO_LOAD
|| fop
== SLO_CHECK
);
3037 DEBUG(desync
, 1, "load: %s", filename
);
3038 return DoLoad(new FileReader(fh
), fop
== SLO_CHECK
);
3040 /* This code may be executed both for old and new save games. */
3041 ClearSaveLoadState();
3043 /* Skip the "colour" character */
3044 if (fop
!= SLO_CHECK
) DEBUG(sl
, 0, "%s", GetSaveLoadErrorString() + 3);
3046 /* A saver/loader exception!! reinitialize all variables to prevent crash! */
3047 return (fop
== SLO_LOAD
) ? SL_REINIT
: SL_ERROR
;
3051 /** Do a save when exiting the game (_settings_client.gui.autosave_on_exit) */
3054 SaveOrLoad("exit.sav", SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
);
3058 * Fill the buffer with the default name for a savegame *or* screenshot.
3059 * @param buf the buffer to write to.
3060 * @param last the last element in the buffer.
3062 void GenerateDefaultSaveName(char *buf
, const char *last
)
3064 /* Check if we have a name for this map, which is the name of the first
3065 * available company. When there's no company available we'll use
3066 * 'Spectator' as "company" name. */
3067 CompanyID cid
= _local_company
;
3068 if (!Company::IsValidID(cid
)) {
3070 FOR_ALL_COMPANIES(c
) {
3078 /* Insert current date */
3079 switch (_settings_client
.gui
.date_format_in_default_names
) {
3080 case 0: SetDParam(1, STR_JUST_DATE_LONG
); break;
3081 case 1: SetDParam(1, STR_JUST_DATE_TINY
); break;
3082 case 2: SetDParam(1, STR_JUST_DATE_ISO
); break;
3083 default: NOT_REACHED();
3085 SetDParam(2, _date
);
3087 /* Get the correct string (special string for when there's not company) */
3088 GetString(buf
, !Company::IsValidID(cid
) ? STR_SAVEGAME_NAME_SPECTATOR
: STR_SAVEGAME_NAME_DEFAULT
, last
);
3089 SanitizeFilename(buf
);
3093 * Set the mode and file type of the file to save or load based on the type of file entry at the file system.
3094 * @param ft Type of file entry of the file system.
3096 void FileToSaveLoad::SetMode(FiosType ft
)
3098 this->SetMode(SLO_LOAD
, GetAbstractFileType(ft
), GetDetailedFileType(ft
));
3102 * Set the mode and file type of the file to save or load.
3103 * @param fop File operation being performed.
3104 * @param aft Abstract file type.
3105 * @param dft Detailed file type.
3107 void FileToSaveLoad::SetMode(SaveLoadOperation fop
, AbstractFileType aft
, DetailedFileType dft
)
3109 if (aft
== FT_INVALID
|| aft
== FT_NONE
) {
3110 this->file_op
= SLO_INVALID
;
3111 this->detail_ftype
= DFT_INVALID
;
3112 this->abstract_ftype
= FT_INVALID
;
3116 this->file_op
= fop
;
3117 this->detail_ftype
= dft
;
3118 this->abstract_ftype
= aft
;
3122 * Set the name of the file.
3123 * @param name Name of the file.
3125 void FileToSaveLoad::SetName(const char *name
)
3127 strecpy(this->name
, name
, lastof(this->name
));
3131 * Set the title of the file.
3132 * @param title Title of the file.
3134 void FileToSaveLoad::SetTitle(const char *title
)
3136 strecpy(this->title
, title
, lastof(this->title
));
3141 * Function to get the type of the savegame by looking at the file header.
3142 * NOTICE: Not used right now, but could be used if extensions of savegames are garbled
3143 * @param file Savegame to be checked
3144 * @return SL_OLD_LOAD or SL_LOAD of the file
3146 int GetSavegameType(char *file
)
3148 const SaveLoadFormat
*fmt
;
3151 int mode
= SL_OLD_LOAD
;
3153 f
= fopen(file
, "rb");
3154 if (fread(&hdr
, sizeof(hdr
), 1, f
) != 1) {
3155 DEBUG(sl
, 0, "Savegame is obsolete or invalid format");
3156 mode
= SL_LOAD
; // don't try to get filename, just show name as it is written
3158 /* see if we have any loader for this type. */
3159 for (fmt
= _saveload_formats
; fmt
!= endof(_saveload_formats
); fmt
++) {
3160 if (fmt
->tag
== hdr
) {
3161 mode
= SL_LOAD
; // new type of savegame