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
304 * 283 SL_PATCH_PACK_1_24
306 extern const uint16 SAVEGAME_VERSION
= SL_PATCH_PACK_1_24
; ///< Current savegame version of OpenTTD.
308 SavegameType _savegame_type
; ///< type of savegame we are loading
309 FileToSaveLoad _file_to_saveload
; ///< File to save or load in the openttd loop.
311 uint32 _ttdp_version
; ///< version of TTDP savegame (if applicable)
312 uint16 _sl_version
; ///< the major savegame version identifier
313 byte _sl_minor_version
; ///< the minor savegame version, DO NOT USE!
314 char _savegame_format
[8]; ///< how to compress savegames
315 bool _do_autosave
; ///< are we doing an autosave at the moment?
317 /** What are we currently doing? */
318 enum SaveLoadAction
{
319 SLA_LOAD
, ///< loading
320 SLA_SAVE
, ///< saving
321 SLA_PTRS
, ///< fixing pointers
322 SLA_NULL
, ///< null all pointers (on loading error)
323 SLA_LOAD_CHECK
, ///< partial loading into #_load_check_data
327 NL_NONE
= 0, ///< not working in NeedLength mode
328 NL_WANTLENGTH
= 1, ///< writing length and data
329 NL_CALCLENGTH
= 2, ///< need to calculate the length
332 /** Save in chunks of 128 KiB. */
333 static const size_t MEMORY_CHUNK_SIZE
= 128 * 1024;
335 /** A buffer for reading (and buffering) savegame data. */
337 byte buf
[MEMORY_CHUNK_SIZE
]; ///< Buffer we're going to read from.
338 byte
*bufp
; ///< Location we're at reading the buffer.
339 byte
*bufe
; ///< End of the buffer we can read from.
340 LoadFilter
*reader
; ///< The filter used to actually read.
341 size_t read
; ///< The amount of read bytes so far from the filter.
344 * Initialise our variables.
345 * @param reader The filter to actually read data.
347 ReadBuffer(LoadFilter
*reader
) : bufp(NULL
), bufe(NULL
), reader(reader
), read(0)
351 inline byte
ReadByte()
353 if (this->bufp
== this->bufe
) {
354 size_t len
= this->reader
->Read(this->buf
, lengthof(this->buf
));
355 if (len
== 0) SlErrorCorrupt("Unexpected end of chunk");
358 this->bufp
= this->buf
;
359 this->bufe
= this->buf
+ len
;
362 return *this->bufp
++;
366 * Get the size of the memory dump made so far.
369 size_t GetSize() const
371 return this->read
- (this->bufe
- this->bufp
);
376 /** Container for dumping the savegame (quickly) to memory. */
377 struct MemoryDumper
{
378 AutoFreeSmallVector
<byte
*, 16> blocks
; ///< Buffer with blocks of allocated memory.
379 byte
*buf
; ///< Buffer we're going to write to.
380 byte
*bufe
; ///< End of the buffer we write to.
382 /** Initialise our variables. */
383 MemoryDumper() : buf(NULL
), bufe(NULL
)
388 * Write a single byte into the dumper.
389 * @param b The byte to write.
391 inline void WriteByte(byte b
)
393 /* Are we at the end of this chunk? */
394 if (this->buf
== this->bufe
) {
395 this->buf
= CallocT
<byte
>(MEMORY_CHUNK_SIZE
);
396 *this->blocks
.Append() = this->buf
;
397 this->bufe
= this->buf
+ MEMORY_CHUNK_SIZE
;
404 * Flush this dumper into a writer.
405 * @param writer The filter we want to use.
407 void Flush(SaveFilter
*writer
)
410 size_t t
= this->GetSize();
413 size_t to_write
= min(MEMORY_CHUNK_SIZE
, t
);
415 writer
->Write(this->blocks
[i
++], to_write
);
423 * Get the size of the memory dump made so far.
426 size_t GetSize() const
428 return this->blocks
.Length() * MEMORY_CHUNK_SIZE
- (this->bufe
- this->buf
);
432 /** The saveload struct, containing reader-writer functions, buffer, version, etc. */
433 struct SaveLoadParams
{
434 SaveLoadAction action
; ///< are we doing a save or a load atm.
435 NeedLength need_length
; ///< working in NeedLength (Autolength) mode?
436 byte block_mode
; ///< ???
437 bool error
; ///< did an error occur or not
439 size_t obj_len
; ///< the length of the current object we are busy with
440 int array_index
, last_array_index
; ///< in the case of an array, the current and last positions
442 MemoryDumper
*dumper
; ///< Memory dumper to write the savegame to.
443 SaveFilter
*sf
; ///< Filter to write the savegame to.
445 ReadBuffer
*reader
; ///< Savegame reading buffer.
446 LoadFilter
*lf
; ///< Filter to read the savegame from.
448 StringID error_str
; ///< the translatable error message to show
449 char *extra_msg
; ///< the error message
451 byte ff_state
; ///< The state of fast-forward when saving started.
452 bool saveinprogress
; ///< Whether there is currently a save in progress.
455 static SaveLoadParams _sl
; ///< Parameters used for/at saveload.
457 /* these define the chunks */
458 extern const ChunkHandler _gamelog_chunk_handlers
[];
459 extern const ChunkHandler _map_chunk_handlers
[];
460 extern const ChunkHandler _misc_chunk_handlers
[];
461 extern const ChunkHandler _name_chunk_handlers
[];
462 extern const ChunkHandler _cheat_chunk_handlers
[] ;
463 extern const ChunkHandler _setting_chunk_handlers
[];
464 extern const ChunkHandler _company_chunk_handlers
[];
465 extern const ChunkHandler _engine_chunk_handlers
[];
466 extern const ChunkHandler _veh_chunk_handlers
[];
467 extern const ChunkHandler _waypoint_chunk_handlers
[];
468 extern const ChunkHandler _depot_chunk_handlers
[];
469 extern const ChunkHandler _order_chunk_handlers
[];
470 extern const ChunkHandler _town_chunk_handlers
[];
471 extern const ChunkHandler _sign_chunk_handlers
[];
472 extern const ChunkHandler _station_chunk_handlers
[];
473 extern const ChunkHandler _industry_chunk_handlers
[];
474 extern const ChunkHandler _economy_chunk_handlers
[];
475 extern const ChunkHandler _subsidy_chunk_handlers
[];
476 extern const ChunkHandler _cargomonitor_chunk_handlers
[];
477 extern const ChunkHandler _goal_chunk_handlers
[];
478 extern const ChunkHandler _story_page_chunk_handlers
[];
479 extern const ChunkHandler _ai_chunk_handlers
[];
480 extern const ChunkHandler _game_chunk_handlers
[];
481 extern const ChunkHandler _animated_tile_chunk_handlers
[];
482 extern const ChunkHandler _newgrf_chunk_handlers
[];
483 extern const ChunkHandler _group_chunk_handlers
[];
484 extern const ChunkHandler _cargopacket_chunk_handlers
[];
485 extern const ChunkHandler _autoreplace_chunk_handlers
[];
486 extern const ChunkHandler _labelmaps_chunk_handlers
[];
487 extern const ChunkHandler _linkgraph_chunk_handlers
[];
488 extern const ChunkHandler _airport_chunk_handlers
[];
489 extern const ChunkHandler _object_chunk_handlers
[];
490 extern const ChunkHandler _persistent_storage_chunk_handlers
[];
491 extern const ChunkHandler _plan_chunk_handlers
[];
492 extern const ChunkHandler _trace_restrict_chunk_handlers
[];
493 extern const ChunkHandler _template_replacement_chunk_handlers
[];
494 extern const ChunkHandler _template_vehicle_chunk_handlers
[];
495 extern const ChunkHandler _logic_signal_handlers
[];
496 extern const ChunkHandler _bridge_signal_chunk_handlers
[];
497 extern const ChunkHandler _tunnel_chunk_handlers
[];
499 /** Array of all chunks in a savegame, \c NULL terminated. */
500 static const ChunkHandler
* const _chunk_handlers
[] = {
501 _gamelog_chunk_handlers
,
503 _misc_chunk_handlers
,
504 _name_chunk_handlers
,
505 _cheat_chunk_handlers
,
506 _setting_chunk_handlers
,
508 _waypoint_chunk_handlers
,
509 _depot_chunk_handlers
,
510 _order_chunk_handlers
,
511 _industry_chunk_handlers
,
512 _economy_chunk_handlers
,
513 _subsidy_chunk_handlers
,
514 _cargomonitor_chunk_handlers
,
515 _goal_chunk_handlers
,
516 _story_page_chunk_handlers
,
517 _engine_chunk_handlers
,
518 _town_chunk_handlers
,
519 _sign_chunk_handlers
,
520 _station_chunk_handlers
,
521 _company_chunk_handlers
,
523 _game_chunk_handlers
,
524 _animated_tile_chunk_handlers
,
525 _newgrf_chunk_handlers
,
526 _group_chunk_handlers
,
527 _cargopacket_chunk_handlers
,
528 _autoreplace_chunk_handlers
,
529 _labelmaps_chunk_handlers
,
530 _linkgraph_chunk_handlers
,
531 _airport_chunk_handlers
,
532 _object_chunk_handlers
,
533 _persistent_storage_chunk_handlers
,
534 _plan_chunk_handlers
,
535 _trace_restrict_chunk_handlers
,
536 _template_replacement_chunk_handlers
,
537 _template_vehicle_chunk_handlers
,
538 _logic_signal_handlers
,
539 _bridge_signal_chunk_handlers
,
540 _tunnel_chunk_handlers
,
545 * Iterate over all chunk handlers.
546 * @param ch the chunk handler iterator
548 #define FOR_ALL_CHUNK_HANDLERS(ch) \
549 for (const ChunkHandler * const *chsc = _chunk_handlers; *chsc != NULL; chsc++) \
550 for (const ChunkHandler *ch = *chsc; ch != NULL; ch = (ch->flags & CH_LAST) ? NULL : ch + 1)
552 /** Null all pointers (convert index -> NULL) */
553 static void SlNullPointers()
555 _sl
.action
= SLA_NULL
;
557 /* We don't want any savegame conversion code to run
558 * during NULLing; especially those that try to get
559 * pointers from other pools. */
560 _sl_version
= SAVEGAME_VERSION
;
562 DEBUG(sl
, 1, "Nulling pointers");
564 FOR_ALL_CHUNK_HANDLERS(ch
) {
565 if (ch
->ptrs_proc
!= NULL
) {
566 DEBUG(sl
, 2, "Nulling pointers for %c%c%c%c", ch
->id
>> 24, ch
->id
>> 16, ch
->id
>> 8, ch
->id
);
571 DEBUG(sl
, 1, "All pointers nulled");
573 assert(_sl
.action
== SLA_NULL
);
577 * Error handler. Sets everything up to show an error message and to clean
578 * up the mess of a partial savegame load.
579 * @param string The translatable error message to show.
580 * @param extra_msg An extra error message coming from one of the APIs.
581 * @note This function does never return as it throws an exception to
582 * break out of all the saveload code.
584 void NORETURN
SlError(StringID string
, const char *extra_msg
)
586 /* Distinguish between loading into _load_check_data vs. normal save/load. */
587 if (_sl
.action
== SLA_LOAD_CHECK
) {
588 _load_check_data
.error
= string
;
589 free(_load_check_data
.error_data
);
590 _load_check_data
.error_data
= (extra_msg
== NULL
) ? NULL
: stredup(extra_msg
);
592 _sl
.error_str
= string
;
594 _sl
.extra_msg
= (extra_msg
== NULL
) ? NULL
: stredup(extra_msg
);
597 /* We have to NULL all pointers here; we might be in a state where
598 * the pointers are actually filled with indices, which means that
599 * when we access them during cleaning the pool dereferences of
600 * those indices will be made with segmentation faults as result. */
601 if (_sl
.action
== SLA_LOAD
|| _sl
.action
== SLA_PTRS
) SlNullPointers();
602 throw std::exception();
606 * Error handler for corrupt savegames. Sets everything up to show the
607 * error message and to clean up the mess of a partial savegame load.
608 * @param msg Location the corruption has been spotted.
609 * @note This function does never return as it throws an exception to
610 * break out of all the saveload code.
612 void NORETURN
SlErrorCorrupt(const char *msg
)
614 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME
, msg
);
618 typedef void (*AsyncSaveFinishProc
)(); ///< Callback for when the savegame loading is finished.
619 static AsyncSaveFinishProc _async_save_finish
= NULL
; ///< Callback to call when the savegame loading is finished.
620 static ThreadObject
*_save_thread
; ///< The thread we're using to compress and write a savegame
623 * Called by save thread to tell we finished saving.
624 * @param proc The callback to call when saving is done.
626 static void SetAsyncSaveFinish(AsyncSaveFinishProc proc
)
628 if (_exit_game
) return;
629 while (_async_save_finish
!= NULL
) CSleep(10);
631 _async_save_finish
= proc
;
635 * Handle async save finishes.
637 void ProcessAsyncSaveFinish()
639 if (_async_save_finish
== NULL
) return;
641 _async_save_finish();
643 _async_save_finish
= NULL
;
645 if (_save_thread
!= NULL
) {
646 _save_thread
->Join();
653 * Wrapper for reading a byte from the buffer.
654 * @return The read byte.
658 return _sl
.reader
->ReadByte();
662 * Wrapper for writing a byte to the dumper.
663 * @param b The byte to write.
665 void SlWriteByte(byte b
)
667 _sl
.dumper
->WriteByte(b
);
670 static inline int SlReadUint16()
672 int x
= SlReadByte() << 8;
673 return x
| SlReadByte();
676 static inline uint32
SlReadUint32()
678 uint32 x
= SlReadUint16() << 16;
679 return x
| SlReadUint16();
682 static inline uint64
SlReadUint64()
684 uint32 x
= SlReadUint32();
685 uint32 y
= SlReadUint32();
686 return (uint64
)x
<< 32 | y
;
689 static inline void SlWriteUint16(uint16 v
)
691 SlWriteByte(GB(v
, 8, 8));
692 SlWriteByte(GB(v
, 0, 8));
695 static inline void SlWriteUint32(uint32 v
)
697 SlWriteUint16(GB(v
, 16, 16));
698 SlWriteUint16(GB(v
, 0, 16));
701 static inline void SlWriteUint64(uint64 x
)
703 SlWriteUint32((uint32
)(x
>> 32));
704 SlWriteUint32((uint32
)x
);
708 * Read in bytes from the file/data structure but don't do
709 * anything with them, discarding them in effect
710 * @param length The amount of bytes that is being treated this way
712 static inline void SlSkipBytes(size_t length
)
714 for (; length
!= 0; length
--) SlReadByte();
718 * Read in the header descriptor of an object or an array.
719 * If the highest bit is set (7), then the index is bigger than 127
720 * elements, so use the next byte to read in the real value.
721 * The actual value is then both bytes added with the first shifted
722 * 8 bits to the left, and dropping the highest bit (which only indicated a big index).
723 * x = ((x & 0x7F) << 8) + SlReadByte();
724 * @return Return the value of the index
726 static uint
SlReadSimpleGamma()
728 uint i
= SlReadByte();
738 SlErrorCorrupt("Unsupported gamma");
740 i
= SlReadByte(); // 32 bits only.
742 i
= (i
<< 8) | SlReadByte();
744 i
= (i
<< 8) | SlReadByte();
746 i
= (i
<< 8) | SlReadByte();
752 * Write the header descriptor of an object or an array.
753 * If the element is bigger than 127, use 2 bytes for saving
754 * and use the highest byte of the first written one as a notice
755 * that the length consists of 2 bytes, etc.. like this:
758 * 110xxxxx xxxxxxxx xxxxxxxx
759 * 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
760 * 11110--- xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
761 * We could extend the scheme ad infinum to support arbitrarily
762 * large chunks, but as sizeof(size_t) == 4 is still very common
763 * we don't support anything above 32 bits. That's why in the last
764 * case the 3 most significant bits are unused.
765 * @param i Index being written
768 static void SlWriteSimpleGamma(size_t i
)
771 if (i
>= (1 << 14)) {
772 if (i
>= (1 << 21)) {
773 if (i
>= (1 << 28)) {
774 assert(i
<= UINT32_MAX
); // We can only support 32 bits for now.
775 SlWriteByte((byte
)(0xF0));
776 SlWriteByte((byte
)(i
>> 24));
778 SlWriteByte((byte
)(0xE0 | (i
>> 24)));
780 SlWriteByte((byte
)(i
>> 16));
782 SlWriteByte((byte
)(0xC0 | (i
>> 16)));
784 SlWriteByte((byte
)(i
>> 8));
786 SlWriteByte((byte
)(0x80 | (i
>> 8)));
789 SlWriteByte((byte
)i
);
792 /** Return how many bytes used to encode a gamma value */
793 static inline uint
SlGetGammaLength(size_t i
)
795 return 1 + (i
>= (1 << 7)) + (i
>= (1 << 14)) + (i
>= (1 << 21)) + (i
>= (1 << 28));
798 static inline uint
SlReadSparseIndex()
800 return SlReadSimpleGamma();
803 static inline void SlWriteSparseIndex(uint index
)
805 SlWriteSimpleGamma(index
);
808 static inline uint
SlReadArrayLength()
810 return SlReadSimpleGamma();
813 static inline void SlWriteArrayLength(size_t length
)
815 SlWriteSimpleGamma(length
);
818 static inline uint
SlGetArrayLength(size_t length
)
820 return SlGetGammaLength(length
);
824 * Return the size in bytes of a certain type of normal/atomic variable
825 * as it appears in memory. See VarTypes
826 * @param conv VarType type of variable that is used for calculating the size
827 * @return Return the size of this type in bytes
829 static inline uint
SlCalcConvMemLen(VarType conv
)
831 static const byte conv_mem_size
[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
832 byte length
= GB(conv
, 4, 4);
834 switch (length
<< 4) {
839 return SlReadArrayLength();
842 assert(length
< lengthof(conv_mem_size
));
843 return conv_mem_size
[length
];
848 * Return the size in bytes of a certain type of normal/atomic variable
849 * as it appears in a saved game. See VarTypes
850 * @param conv VarType type of variable that is used for calculating the size
851 * @return Return the size of this type in bytes
853 static inline byte
SlCalcConvFileLen(VarType conv
)
855 static const byte conv_file_size
[] = {1, 1, 2, 2, 4, 4, 8, 8, 2};
856 byte length
= GB(conv
, 0, 4);
857 assert(length
< lengthof(conv_file_size
));
858 return conv_file_size
[length
];
861 /** Return the size in bytes of a reference (pointer) */
862 static inline size_t SlCalcRefLen()
864 return IsSavegameVersionBefore(69) ? 2 : 4;
867 void SlSetArrayIndex(uint index
)
869 _sl
.need_length
= NL_WANTLENGTH
;
870 _sl
.array_index
= index
;
873 static size_t _next_offs
;
876 * Iterate through the elements of an array and read the whole thing
877 * @return The index of the object, or -1 if we have reached the end of current block
883 /* After reading in the whole array inside the loop
884 * we must have read in all the data, so we must be at end of current block. */
885 if (_next_offs
!= 0 && _sl
.reader
->GetSize() != _next_offs
) SlErrorCorrupt("Invalid chunk size");
888 uint length
= SlReadArrayLength();
894 _sl
.obj_len
= --length
;
895 _next_offs
= _sl
.reader
->GetSize() + length
;
897 switch (_sl
.block_mode
) {
898 case CH_SPARSE_ARRAY
: index
= (int)SlReadSparseIndex(); break;
899 case CH_ARRAY
: index
= _sl
.array_index
++; break;
901 DEBUG(sl
, 0, "SlIterateArray error");
905 if (length
!= 0) return index
;
910 * Skip an array or sparse array
914 while (SlIterateArray() != -1) {
915 SlSkipBytes(_next_offs
- _sl
.reader
->GetSize());
920 * Sets the length of either a RIFF object or the number of items in an array.
921 * This lets us load an object or an array of arbitrary size
922 * @param length The length of the sought object/array
924 void SlSetLength(size_t length
)
926 assert(_sl
.action
== SLA_SAVE
);
928 switch (_sl
.need_length
) {
930 _sl
.need_length
= NL_NONE
;
931 switch (_sl
.block_mode
) {
933 /* Ugly encoding of >16M RIFF chunks
934 * The lower 24 bits are normal
935 * The uppermost 4 bits are bits 24:27 */
936 assert(length
< (1 << 28));
937 SlWriteUint32((uint32
)((length
& 0xFFFFFF) | ((length
>> 24) << 28)));
940 assert(_sl
.last_array_index
<= _sl
.array_index
);
941 while (++_sl
.last_array_index
<= _sl
.array_index
) {
942 SlWriteArrayLength(1);
944 SlWriteArrayLength(length
+ 1);
946 case CH_SPARSE_ARRAY
:
947 SlWriteArrayLength(length
+ 1 + SlGetArrayLength(_sl
.array_index
)); // Also include length of sparse index.
948 SlWriteSparseIndex(_sl
.array_index
);
950 default: NOT_REACHED();
955 _sl
.obj_len
+= (int)length
;
958 default: NOT_REACHED();
963 * Save/Load bytes. These do not need to be converted to Little/Big Endian
964 * so directly write them or read them to/from file
965 * @param ptr The source or destination of the object being manipulated
966 * @param length number of bytes this fast CopyBytes lasts
968 static void SlCopyBytes(void *ptr
, size_t length
)
970 byte
*p
= (byte
*)ptr
;
972 switch (_sl
.action
) {
975 for (; length
!= 0; length
--) *p
++ = SlReadByte();
978 for (; length
!= 0; length
--) SlWriteByte(*p
++);
980 default: NOT_REACHED();
984 /** Get the length of the current object */
985 size_t SlGetFieldLength()
991 * Return a signed-long version of the value of a setting
992 * @param ptr pointer to the variable
993 * @param conv type of variable, can be a non-clean
994 * type, eg one with other flags because it is parsed
995 * @return returns the value of the pointer-setting
997 int64
ReadValue(const void *ptr
, VarType conv
)
999 switch (GetVarMemType(conv
)) {
1000 case SLE_VAR_BL
: return (*(const bool *)ptr
!= 0);
1001 case SLE_VAR_I8
: return *(const int8
*)ptr
;
1002 case SLE_VAR_U8
: return *(const byte
*)ptr
;
1003 case SLE_VAR_I16
: return *(const int16
*)ptr
;
1004 case SLE_VAR_U16
: return *(const uint16
*)ptr
;
1005 case SLE_VAR_I32
: return *(const int32
*)ptr
;
1006 case SLE_VAR_U32
: return *(const uint32
*)ptr
;
1007 case SLE_VAR_I64
: return *(const int64
*)ptr
;
1008 case SLE_VAR_U64
: return *(const uint64
*)ptr
;
1009 case SLE_VAR_NULL
:return 0;
1010 default: NOT_REACHED();
1015 * Write the value of a setting
1016 * @param ptr pointer to the variable
1017 * @param conv type of variable, can be a non-clean type, eg
1018 * with other flags. It is parsed upon read
1019 * @param val the new value being given to the variable
1021 void WriteValue(void *ptr
, VarType conv
, int64 val
)
1023 switch (GetVarMemType(conv
)) {
1024 case SLE_VAR_BL
: *(bool *)ptr
= (val
!= 0); break;
1025 case SLE_VAR_I8
: *(int8
*)ptr
= val
; break;
1026 case SLE_VAR_U8
: *(byte
*)ptr
= val
; break;
1027 case SLE_VAR_I16
: *(int16
*)ptr
= val
; break;
1028 case SLE_VAR_U16
: *(uint16
*)ptr
= val
; break;
1029 case SLE_VAR_I32
: *(int32
*)ptr
= val
; break;
1030 case SLE_VAR_U32
: *(uint32
*)ptr
= val
; break;
1031 case SLE_VAR_I64
: *(int64
*)ptr
= val
; break;
1032 case SLE_VAR_U64
: *(uint64
*)ptr
= val
; break;
1033 case SLE_VAR_NAME
: *(char**)ptr
= CopyFromOldName(val
); break;
1034 case SLE_VAR_NULL
: break;
1035 default: NOT_REACHED();
1040 * Handle all conversion and typechecking of variables here.
1041 * In the case of saving, read in the actual value from the struct
1042 * and then write them to file, endian safely. Loading a value
1043 * goes exactly the opposite way
1044 * @param ptr The object being filled/read
1045 * @param conv VarType type of the current element of the struct
1047 static void SlSaveLoadConv(void *ptr
, VarType conv
)
1049 switch (_sl
.action
) {
1051 int64 x
= ReadValue(ptr
, conv
);
1053 /* Write the value to the file and check if its value is in the desired range */
1054 switch (GetVarFileType(conv
)) {
1055 case SLE_FILE_I8
: assert(x
>= -128 && x
<= 127); SlWriteByte(x
);break;
1056 case SLE_FILE_U8
: assert(x
>= 0 && x
<= 255); SlWriteByte(x
);break;
1057 case SLE_FILE_I16
:assert(x
>= -32768 && x
<= 32767); SlWriteUint16(x
);break;
1058 case SLE_FILE_STRINGID
:
1059 case SLE_FILE_U16
:assert(x
>= 0 && x
<= 65535); SlWriteUint16(x
);break;
1061 case SLE_FILE_U32
: SlWriteUint32((uint32
)x
);break;
1063 case SLE_FILE_U64
: SlWriteUint64(x
);break;
1064 default: NOT_REACHED();
1068 case SLA_LOAD_CHECK
:
1071 /* Read a value from the file */
1072 switch (GetVarFileType(conv
)) {
1073 case SLE_FILE_I8
: x
= (int8
)SlReadByte(); break;
1074 case SLE_FILE_U8
: x
= (byte
)SlReadByte(); break;
1075 case SLE_FILE_I16
: x
= (int16
)SlReadUint16(); break;
1076 case SLE_FILE_U16
: x
= (uint16
)SlReadUint16(); break;
1077 case SLE_FILE_I32
: x
= (int32
)SlReadUint32(); break;
1078 case SLE_FILE_U32
: x
= (uint32
)SlReadUint32(); break;
1079 case SLE_FILE_I64
: x
= (int64
)SlReadUint64(); break;
1080 case SLE_FILE_U64
: x
= (uint64
)SlReadUint64(); break;
1081 case SLE_FILE_STRINGID
: x
= RemapOldStringID((uint16
)SlReadUint16()); break;
1082 default: NOT_REACHED();
1085 /* Write The value to the struct. These ARE endian safe. */
1086 WriteValue(ptr
, conv
, x
);
1089 case SLA_PTRS
: break;
1090 case SLA_NULL
: break;
1091 default: NOT_REACHED();
1096 * Calculate the net length of a string. This is in almost all cases
1097 * just strlen(), but if the string is not properly terminated, we'll
1098 * resort to the maximum length of the buffer.
1099 * @param ptr pointer to the stringbuffer
1100 * @param length maximum length of the string (buffer). If -1 we don't care
1101 * about a maximum length, but take string length as it is.
1102 * @return return the net length of the string
1104 static inline size_t SlCalcNetStringLen(const char *ptr
, size_t length
)
1106 if (ptr
== NULL
) return 0;
1107 return min(strlen(ptr
), length
- 1);
1111 * Calculate the gross length of the std::string that it
1112 * will occupy in the savegame. This includes the real length,
1113 * and the length that the index will occupy.
1114 * @param str reference to the std::string
1115 * @return return the gross length of the string
1117 static inline size_t SlCalcStdStrLen(const std::string
&str
)
1119 return str
.size() + SlGetArrayLength(str
.size()); // also include the length of the index
1123 * Calculate the gross length of the string that it
1124 * will occupy in the savegame. This includes the real length, returned
1125 * by SlCalcNetStringLen and the length that the index will occupy.
1126 * @param ptr pointer to the stringbuffer
1127 * @param length maximum length of the string (buffer size, etc.)
1128 * @param conv type of data been used
1129 * @return return the gross length of the string
1131 static inline size_t SlCalcStringLen(const void *ptr
, size_t length
, VarType conv
)
1136 switch (GetVarMemType(conv
)) {
1137 default: NOT_REACHED();
1140 str
= *(const char * const *)ptr
;
1145 str
= (const char *)ptr
;
1150 len
= SlCalcNetStringLen(str
, len
);
1151 return len
+ SlGetArrayLength(len
); // also include the length of the index
1155 * Save/Load a string.
1156 * @param ptr the string being manipulated
1157 * @param length of the string (full length)
1158 * @param conv must be SLE_FILE_STRING
1160 static void SlString(void *ptr
, size_t length
, VarType conv
)
1162 switch (_sl
.action
) {
1165 switch (GetVarMemType(conv
)) {
1166 default: NOT_REACHED();
1169 len
= SlCalcNetStringLen((char *)ptr
, length
);
1173 ptr
= *(char **)ptr
;
1174 len
= SlCalcNetStringLen((char *)ptr
, SIZE_MAX
);
1178 SlWriteArrayLength(len
);
1179 SlCopyBytes(ptr
, len
);
1182 case SLA_LOAD_CHECK
:
1184 size_t len
= SlReadArrayLength();
1186 switch (GetVarMemType(conv
)) {
1187 default: NOT_REACHED();
1190 if (len
>= length
) {
1191 DEBUG(sl
, 1, "String length in savegame is bigger than buffer, truncating");
1192 SlCopyBytes(ptr
, length
);
1193 SlSkipBytes(len
- length
);
1196 SlCopyBytes(ptr
, len
);
1200 case SLE_VAR_STRQ
: // Malloc'd string, free previous incarnation, and allocate
1201 free(*(char **)ptr
);
1203 *(char **)ptr
= NULL
;
1206 *(char **)ptr
= MallocT
<char>(len
+ 1); // terminating '\0'
1207 ptr
= *(char **)ptr
;
1208 SlCopyBytes(ptr
, len
);
1213 ((char *)ptr
)[len
] = '\0'; // properly terminate the string
1214 StringValidationSettings settings
= SVS_REPLACE_WITH_QUESTION_MARK
;
1215 if ((conv
& SLF_ALLOW_CONTROL
) != 0) {
1216 settings
= settings
| SVS_ALLOW_CONTROL_CODE
;
1217 if (IsSavegameVersionBefore(169)) {
1218 str_fix_scc_encoded((char *)ptr
, (char *)ptr
+ len
);
1221 if ((conv
& SLF_ALLOW_NEWLINE
) != 0) {
1222 settings
= settings
| SVS_ALLOW_NEWLINE
;
1224 str_validate((char *)ptr
, (char *)ptr
+ len
, settings
);
1227 case SLA_PTRS
: break;
1228 case SLA_NULL
: break;
1229 default: NOT_REACHED();
1234 * Save/Load a std::string.
1235 * @param ptr the std::string being manipulated
1236 * @param conv must be SLE_FILE_STRING
1238 static void SlStdString(std::string
&str
, VarType conv
)
1240 switch (_sl
.action
) {
1242 SlWriteArrayLength(str
.size());
1243 SlCopyBytes(const_cast<char *>(str
.data()), str
.size());
1246 case SLA_LOAD_CHECK
:
1248 size_t len
= SlReadArrayLength();
1250 SlCopyBytes(const_cast<char *>(str
.c_str()), len
);
1252 StringValidationSettings settings
= SVS_REPLACE_WITH_QUESTION_MARK
;
1253 if ((conv
& SLF_ALLOW_CONTROL
) != 0) {
1254 settings
= settings
| SVS_ALLOW_CONTROL_CODE
;
1256 if ((conv
& SLF_ALLOW_NEWLINE
) != 0) {
1257 settings
= settings
| SVS_ALLOW_NEWLINE
;
1259 str_validate(str
, settings
);
1262 case SLA_PTRS
: break;
1263 case SLA_NULL
: break;
1264 default: NOT_REACHED();
1269 * Return the size in bytes of a certain type of atomic array
1270 * @param length The length of the array counted in elements
1271 * @param conv VarType type of the variable that is used in calculating the size
1273 static inline size_t SlCalcArrayLen(size_t length
, VarType conv
)
1275 return SlCalcConvFileLen(conv
) * length
;
1279 * Save/Load an array.
1280 * @param array The array being manipulated
1281 * @param length The length of the array in elements
1282 * @param conv VarType type of the atomic array (int, byte, uint64, etc.)
1284 void SlArray(void *array
, size_t length
, VarType conv
)
1286 if (_sl
.action
== SLA_PTRS
|| _sl
.action
== SLA_NULL
) return;
1288 /* Automatically calculate the length? */
1289 if (_sl
.need_length
!= NL_NONE
) {
1290 SlSetLength(SlCalcArrayLen(length
, conv
));
1291 /* Determine length only? */
1292 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1295 /* NOTICE - handle some buggy stuff, in really old versions everything was saved
1296 * as a byte-type. So detect this, and adjust array size accordingly */
1297 if (_sl
.action
!= SLA_SAVE
&& _sl_version
== 0) {
1298 /* all arrays except difficulty settings */
1299 if (conv
== SLE_INT16
|| conv
== SLE_UINT16
|| conv
== SLE_STRINGID
||
1300 conv
== SLE_INT32
|| conv
== SLE_UINT32
) {
1301 SlCopyBytes(array
, length
* SlCalcConvFileLen(conv
));
1304 /* used for conversion of Money 32bit->64bit */
1305 if (conv
== (SLE_FILE_I32
| SLE_VAR_I64
)) {
1306 for (uint i
= 0; i
< length
; i
++) {
1307 ((int64
*)array
)[i
] = (int32
)BSWAP32(SlReadUint32());
1313 /* If the size of elements is 1 byte both in file and memory, no special
1314 * conversion is needed, use specialized copy-copy function to speed up things */
1315 if (conv
== SLE_INT8
|| conv
== SLE_UINT8
) {
1316 SlCopyBytes(array
, length
);
1318 byte
*a
= (byte
*)array
;
1319 byte mem_size
= SlCalcConvMemLen(conv
);
1321 for (; length
!= 0; length
--) {
1322 SlSaveLoadConv(a
, conv
);
1323 a
+= mem_size
; // get size
1330 * Pointers cannot be saved to a savegame, so this functions gets
1331 * the index of the item, and if not available, it hussles with
1332 * pointers (looks really bad :()
1333 * Remember that a NULL item has value 0, and all
1334 * indices have +1, so vehicle 0 is saved as index 1.
1335 * @param obj The object that we want to get the index of
1336 * @param rt SLRefType type of the object the index is being sought of
1337 * @return Return the pointer converted to an index of the type pointed to
1339 static size_t ReferenceToInt(const void *obj
, SLRefType rt
)
1341 assert(_sl
.action
== SLA_SAVE
);
1343 if (obj
== NULL
) return 0;
1346 case REF_VEHICLE_OLD
: // Old vehicles we save as new ones
1347 case REF_VEHICLE
: return ((const Vehicle
*)obj
)->index
+ 1;
1348 case REF_TEMPLATE_VEHICLE
: return ((const TemplateVehicle
*)obj
)->index
+ 1;
1349 case REF_STATION
: return ((const Station
*)obj
)->index
+ 1;
1350 case REF_TOWN
: return ((const Town
*)obj
)->index
+ 1;
1351 case REF_ORDER
: return ((const Order
*)obj
)->index
+ 1;
1352 case REF_ROADSTOPS
: return ((const RoadStop
*)obj
)->index
+ 1;
1353 case REF_ENGINE_RENEWS
: return ((const EngineRenew
*)obj
)->index
+ 1;
1354 case REF_CARGO_PACKET
: return ((const CargoPacket
*)obj
)->index
+ 1;
1355 case REF_ORDERLIST
: return ((const OrderList
*)obj
)->index
+ 1;
1356 case REF_STORAGE
: return ((const PersistentStorage
*)obj
)->index
+ 1;
1357 case REF_LINK_GRAPH
: return ((const LinkGraph
*)obj
)->index
+ 1;
1358 case REF_LINK_GRAPH_JOB
: return ((const LinkGraphJob
*)obj
)->index
+ 1;
1359 case REF_DOCKS
: return ((const Dock
*)obj
)->index
+ 1;
1360 default: NOT_REACHED();
1365 * Pointers cannot be loaded from a savegame, so this function
1366 * gets the index from the savegame and returns the appropriate
1367 * pointer from the already loaded base.
1368 * Remember that an index of 0 is a NULL pointer so all indices
1369 * are +1 so vehicle 0 is saved as 1.
1370 * @param index The index that is being converted to a pointer
1371 * @param rt SLRefType type of the object the pointer is sought of
1372 * @return Return the index converted to a pointer of any type
1374 static void *IntToReference(size_t index
, SLRefType rt
)
1376 assert_compile(sizeof(size_t) <= sizeof(void *));
1378 assert(_sl
.action
== SLA_PTRS
);
1380 /* After version 4.3 REF_VEHICLE_OLD is saved as REF_VEHICLE,
1381 * and should be loaded like that */
1382 if (rt
== REF_VEHICLE_OLD
&& !IsSavegameVersionBefore(4, 4)) {
1386 /* No need to look up NULL pointers, just return immediately */
1387 if (index
== (rt
== REF_VEHICLE_OLD
? 0xFFFF : 0)) return NULL
;
1389 /* Correct index. Old vehicles were saved differently:
1390 * invalid vehicle was 0xFFFF, now we use 0x0000 for everything invalid. */
1391 if (rt
!= REF_VEHICLE_OLD
) index
--;
1395 if (OrderList::IsValidID(index
)) return OrderList::Get(index
);
1396 SlErrorCorrupt("Referencing invalid OrderList");
1399 if (Order::IsValidID(index
)) return Order::Get(index
);
1400 /* in old versions, invalid order was used to mark end of order list */
1401 if (IsSavegameVersionBefore(5, 2)) return NULL
;
1402 SlErrorCorrupt("Referencing invalid Order");
1404 case REF_VEHICLE_OLD
:
1406 if (Vehicle::IsValidID(index
)) return Vehicle::Get(index
);
1407 SlErrorCorrupt("Referencing invalid Vehicle");
1409 case REF_TEMPLATE_VEHICLE
:
1410 if (TemplateVehicle::IsValidID(index
)) return TemplateVehicle::Get(index
);
1411 SlErrorCorrupt("Referencing invalid TemplateVehicle");
1414 if (Station::IsValidID(index
)) return Station::Get(index
);
1415 SlErrorCorrupt("Referencing invalid Station");
1418 if (Town::IsValidID(index
)) return Town::Get(index
);
1419 SlErrorCorrupt("Referencing invalid Town");
1422 if (RoadStop::IsValidID(index
)) return RoadStop::Get(index
);
1423 SlErrorCorrupt("Referencing invalid RoadStop");
1426 if (Dock::IsValidID(index
)) return Dock::Get(index
);
1427 SlErrorCorrupt("Referencing invalid Dock");
1429 case REF_ENGINE_RENEWS
:
1430 if (EngineRenew::IsValidID(index
)) return EngineRenew::Get(index
);
1431 SlErrorCorrupt("Referencing invalid EngineRenew");
1433 case REF_CARGO_PACKET
:
1434 if (CargoPacket::IsValidID(index
)) return CargoPacket::Get(index
);
1435 SlErrorCorrupt("Referencing invalid CargoPacket");
1438 if (PersistentStorage::IsValidID(index
)) return PersistentStorage::Get(index
);
1439 SlErrorCorrupt("Referencing invalid PersistentStorage");
1441 case REF_LINK_GRAPH
:
1442 if (LinkGraph::IsValidID(index
)) return LinkGraph::Get(index
);
1443 SlErrorCorrupt("Referencing invalid LinkGraph");
1445 case REF_LINK_GRAPH_JOB
:
1446 if (LinkGraphJob::IsValidID(index
)) return LinkGraphJob::Get(index
);
1447 SlErrorCorrupt("Referencing invalid LinkGraphJob");
1449 default: NOT_REACHED();
1454 * Return the size in bytes of a list
1455 * @param list The std::list to find the size of
1457 template<typename PtrList
>
1458 static inline size_t SlCalcListLen(const void *list
)
1460 const PtrList
*l
= (const PtrList
*)list
;
1462 int type_size
= IsSavegameVersionBefore(69) ? 2 : 4;
1463 /* Each entry is saved as type_size bytes, plus type_size bytes are used for the length
1465 return l
->size() * type_size
+ type_size
;
1469 * Return the size in bytes of a list
1470 * @param list The std::list to find the size of
1472 template<typename PtrList
>
1473 static inline size_t SlCalcVarListLen(const void *list
, size_t item_size
)
1475 const PtrList
*l
= (const PtrList
*) list
;
1476 /* Each entry is saved as item_size bytes, plus 4 bytes are used for the length
1478 return l
->size() * item_size
+ 4;
1484 * @param list The list being manipulated
1485 * @param conv SLRefType type of the list (Vehicle *, Station *, etc)
1487 template<typename PtrList
>
1488 static void SlList(void *list
, SLRefType conv
)
1490 /* Automatically calculate the length? */
1491 if (_sl
.need_length
!= NL_NONE
) {
1492 SlSetLength(SlCalcListLen
<PtrList
>(list
));
1493 /* Determine length only? */
1494 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1497 PtrList
*l
= (PtrList
*)list
;
1499 switch (_sl
.action
) {
1501 SlWriteUint32((uint32
)l
->size());
1503 typename
PtrList::iterator iter
;
1504 for (iter
= l
->begin(); iter
!= l
->end(); ++iter
) {
1506 SlWriteUint32((uint32
)ReferenceToInt(ptr
, conv
));
1510 case SLA_LOAD_CHECK
:
1512 size_t length
= IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1514 /* Load each reference and push to the end of the list */
1515 for (size_t i
= 0; i
< length
; i
++) {
1516 size_t data
= IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1517 l
->push_back((void *)data
);
1525 typename
PtrList::iterator iter
;
1526 for (iter
= temp
.begin(); iter
!= temp
.end(); ++iter
) {
1527 void *ptr
= IntToReference((size_t)*iter
, conv
);
1535 default: NOT_REACHED();
1541 * @param list The list being manipulated
1542 * @param conv VarType type of the list
1544 template<typename PtrList
>
1545 static void SlVarList(void *list
, VarType conv
)
1547 const size_t size_len
= SlCalcConvMemLen(conv
);
1548 /* Automatically calculate the length? */
1549 if (_sl
.need_length
!= NL_NONE
) {
1550 SlSetLength(SlCalcVarListLen
<PtrList
>(list
, size_len
));
1551 /* Determine length only? */
1552 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1555 PtrList
*l
= (PtrList
*)list
;
1557 switch (_sl
.action
) {
1559 SlWriteUint32((uint32
)l
->size());
1561 typename
PtrList::iterator iter
;
1562 for (iter
= l
->begin(); iter
!= l
->end(); ++iter
) {
1563 SlSaveLoadConv(&(*iter
), conv
);
1567 case SLA_LOAD_CHECK
:
1569 size_t length
= SlReadUint32();
1572 typename
PtrList::iterator iter
;
1575 for (size_t i
= 0; i
< length
; i
++) {
1576 SlSaveLoadConv(&(*iter
), conv
);
1581 case SLA_PTRS
: break;
1585 default: NOT_REACHED();
1590 /** Are we going to save this object or not? */
1591 static inline bool SlIsObjectValidInSavegame(const SaveLoad
*sld
)
1593 if (_sl_version
< sld
->version_from
|| _sl_version
> sld
->version_to
) return false;
1594 if (sld
->conv
& SLF_NOT_IN_SAVE
) return false;
1600 * Are we going to load this variable when loading a savegame or not?
1601 * @note If the variable is skipped it is skipped in the savegame
1602 * bytestream itself as well, so there is no need to skip it somewhere else
1604 static inline bool SlSkipVariableOnLoad(const SaveLoad
*sld
)
1606 if ((sld
->conv
& SLF_NO_NETWORK_SYNC
) && _sl
.action
!= SLA_SAVE
&& _networking
&& !_network_server
) {
1607 SlSkipBytes(SlCalcConvMemLen(sld
->conv
) * sld
->length
);
1615 * Calculate the size of an object.
1616 * @param object to be measured
1617 * @param sld The SaveLoad description of the object so we know how to manipulate it
1618 * @return size of given object
1620 size_t SlCalcObjLength(const void *object
, const SaveLoad
*sld
)
1624 /* Need to determine the length and write a length tag. */
1625 for (; sld
->cmd
!= SL_END
; sld
++) {
1626 length
+= SlCalcObjMemberLength(object
, sld
);
1631 size_t SlCalcObjMemberLength(const void *object
, const SaveLoad
*sld
)
1633 assert(_sl
.action
== SLA_SAVE
);
1645 /* CONDITIONAL saveload types depend on the savegame version */
1646 if (!SlIsObjectValidInSavegame(sld
)) break;
1649 case SL_VAR
: return SlCalcConvFileLen(sld
->conv
);
1650 case SL_REF
: return SlCalcRefLen();
1651 case SL_ARR
: return SlCalcArrayLen(sld
->length
, sld
->conv
);
1652 case SL_STR
: return SlCalcStringLen(GetVariableAddress(object
, sld
), sld
->length
, sld
->conv
);
1653 case SL_LST
: return SlCalcListLen
<std::list
<void *>>(GetVariableAddress(object
, sld
));
1654 case SL_DEQ
: return SlCalcListLen
<std::deque
<void *>>(GetVariableAddress(object
, sld
));
1655 case SL_VEC
: return SlCalcListLen
<std::vector
<void *>>(GetVariableAddress(object
, sld
));
1657 const size_t size_len
= SlCalcConvMemLen(sld
->conv
);
1659 case 1: return SlCalcVarListLen
<std::vector
<byte
>>(GetVariableAddress(object
, sld
), 1);
1660 case 2: return SlCalcVarListLen
<std::vector
<uint16
>>(GetVariableAddress(object
, sld
), 2);
1661 case 4: return SlCalcVarListLen
<std::vector
<uint32
>>(GetVariableAddress(object
, sld
), 4);
1662 case 8: return SlCalcVarListLen
<std::vector
<uint64
>>(GetVariableAddress(object
, sld
), 8);
1663 default: NOT_REACHED();
1666 case SL_STDSTR
: return SlCalcStdStrLen(*static_cast<std::string
*>(GetVariableAddress(object
, sld
)));
1667 default: NOT_REACHED();
1670 case SL_WRITEBYTE
: return 1; // a byte is logically of size 1
1671 case SL_VEH_INCLUDE
: return SlCalcObjLength(object
, GetVehicleDescription(VEH_END
));
1672 case SL_ST_INCLUDE
: return SlCalcObjLength(object
, GetBaseStationDescription());
1673 default: NOT_REACHED();
1681 * Check whether the variable size of the variable in the saveload configuration
1682 * matches with the actual variable size.
1683 * @param sld The saveload configuration to test.
1685 static bool IsVariableSizeRight(const SaveLoad
*sld
)
1689 switch (GetVarMemType(sld
->conv
)) {
1691 return sld
->size
== sizeof(bool);
1694 return sld
->size
== sizeof(int8
);
1697 return sld
->size
== sizeof(int16
);
1700 return sld
->size
== sizeof(int32
);
1703 return sld
->size
== sizeof(int64
);
1705 return sld
->size
== sizeof(void *);
1708 /* These should all be pointer sized. */
1709 return sld
->size
== sizeof(void *);
1712 /* These should be pointer sized, or fixed array. */
1713 return sld
->size
== sizeof(void *) || sld
->size
== sld
->length
;
1716 return sld
->size
== sizeof(std::string
);
1723 #endif /* OTTD_ASSERT */
1725 bool SlObjectMember(void *ptr
, const SaveLoad
*sld
)
1728 assert(IsVariableSizeRight(sld
));
1731 VarType conv
= GB(sld
->conv
, 0, 8);
1742 /* CONDITIONAL saveload types depend on the savegame version */
1743 if (!SlIsObjectValidInSavegame(sld
)) return false;
1744 if (SlSkipVariableOnLoad(sld
)) return false;
1747 case SL_VAR
: SlSaveLoadConv(ptr
, conv
); break;
1748 case SL_REF
: // Reference variable, translate
1749 switch (_sl
.action
) {
1751 SlWriteUint32((uint32
)ReferenceToInt(*(void **)ptr
, (SLRefType
)conv
));
1753 case SLA_LOAD_CHECK
:
1755 *(size_t *)ptr
= IsSavegameVersionBefore(69) ? SlReadUint16() : SlReadUint32();
1758 *(void **)ptr
= IntToReference(*(size_t *)ptr
, (SLRefType
)conv
);
1761 *(void **)ptr
= NULL
;
1763 default: NOT_REACHED();
1766 case SL_ARR
: SlArray(ptr
, sld
->length
, conv
); break;
1767 case SL_STR
: SlString(ptr
, sld
->length
, sld
->conv
); break;
1768 case SL_LST
: SlList
<std::list
<void *>>(ptr
, (SLRefType
)conv
); break;
1769 case SL_DEQ
: SlList
<std::deque
<void *>>(ptr
, (SLRefType
)conv
); break;
1770 case SL_VEC
: SlList
<std::vector
<void *>>(ptr
, (SLRefType
)conv
); break;
1772 const size_t size_len
= SlCalcConvMemLen(sld
->conv
);
1774 case 1: SlVarList
<std::vector
<byte
>>(ptr
, conv
); break;
1775 case 2: SlVarList
<std::vector
<uint16
>>(ptr
, conv
); break;
1776 case 4: SlVarList
<std::vector
<uint32
>>(ptr
, conv
); break;
1777 case 8: SlVarList
<std::vector
<uint64
>>(ptr
, conv
); break;
1778 default: NOT_REACHED();
1782 case SL_STDSTR
: SlStdString(*static_cast<std::string
*>(ptr
), sld
->conv
); break;
1783 default: NOT_REACHED();
1787 /* SL_WRITEBYTE translates a value of a variable to another one upon
1788 * saving or loading.
1789 * XXX - variable renaming abuse
1790 * game_value: the value of the variable ingame is abused by sld->version_from
1791 * file_value: the value of the variable in the savegame is abused by sld->version_to */
1793 switch (_sl
.action
) {
1794 case SLA_SAVE
: SlWriteByte(sld
->version_to
); break;
1795 case SLA_LOAD_CHECK
:
1796 case SLA_LOAD
: *(byte
*)ptr
= sld
->version_from
; break;
1797 case SLA_PTRS
: break;
1798 case SLA_NULL
: break;
1799 default: NOT_REACHED();
1803 /* SL_VEH_INCLUDE loads common code for vehicles */
1804 case SL_VEH_INCLUDE
:
1805 SlObject(ptr
, GetVehicleDescription(VEH_END
));
1809 SlObject(ptr
, GetBaseStationDescription());
1812 default: NOT_REACHED();
1818 * Main SaveLoad function.
1819 * @param object The object that is being saved or loaded
1820 * @param sld The SaveLoad description of the object so we know how to manipulate it
1822 void SlObject(void *object
, const SaveLoad
*sld
)
1824 /* Automatically calculate the length? */
1825 if (_sl
.need_length
!= NL_NONE
) {
1826 SlSetLength(SlCalcObjLength(object
, sld
));
1827 if (_sl
.need_length
== NL_CALCLENGTH
) return;
1830 for (; sld
->cmd
!= SL_END
; sld
++) {
1831 void *ptr
= sld
->global
? sld
->address
: GetVariableAddress(object
, sld
);
1832 SlObjectMember(ptr
, sld
);
1837 * Save or Load (a list of) global variables
1838 * @param sldg The global variable that is being loaded or saved
1840 void SlGlobList(const SaveLoadGlobVarList
*sldg
)
1842 SlObject(NULL
, (const SaveLoad
*)sldg
);
1846 * Do something of which I have no idea what it is :P
1847 * @param proc The callback procedure that is called
1848 * @param arg The variable that will be used for the callback procedure
1850 void SlAutolength(AutolengthProc
*proc
, void *arg
)
1854 assert(_sl
.action
== SLA_SAVE
);
1856 /* Tell it to calculate the length */
1857 _sl
.need_length
= NL_CALCLENGTH
;
1862 _sl
.need_length
= NL_WANTLENGTH
;
1863 SlSetLength(_sl
.obj_len
);
1865 offs
= _sl
.dumper
->GetSize() + _sl
.obj_len
;
1867 /* And write the stuff */
1870 if (offs
!= _sl
.dumper
->GetSize()) SlErrorCorrupt("Invalid chunk size");
1874 * Load a chunk of data (eg vehicles, stations, etc.)
1875 * @param ch The chunkhandler that will be used for the operation
1877 static void SlLoadChunk(const ChunkHandler
*ch
)
1879 byte m
= SlReadByte();
1888 _sl
.array_index
= 0;
1890 if (_next_offs
!= 0) SlErrorCorrupt("Invalid array length");
1892 case CH_SPARSE_ARRAY
:
1894 if (_next_offs
!= 0) SlErrorCorrupt("Invalid array length");
1897 if ((m
& 0xF) == CH_RIFF
) {
1899 len
= (SlReadByte() << 16) | ((m
>> 4) << 24);
1900 len
+= SlReadUint16();
1902 endoffs
= _sl
.reader
->GetSize() + len
;
1904 if (_sl
.reader
->GetSize() != endoffs
) SlErrorCorrupt("Invalid chunk size");
1906 SlErrorCorrupt("Invalid chunk type");
1913 * Load a chunk of data for checking savegames.
1914 * If the chunkhandler is NULL, the chunk is skipped.
1915 * @param ch The chunkhandler that will be used for the operation
1917 static void SlLoadCheckChunk(const ChunkHandler
*ch
)
1919 byte m
= SlReadByte();
1928 _sl
.array_index
= 0;
1929 if (ch
->load_check_proc
) {
1930 ch
->load_check_proc();
1935 case CH_SPARSE_ARRAY
:
1936 if (ch
->load_check_proc
) {
1937 ch
->load_check_proc();
1943 if ((m
& 0xF) == CH_RIFF
) {
1945 len
= (SlReadByte() << 16) | ((m
>> 4) << 24);
1946 len
+= SlReadUint16();
1948 endoffs
= _sl
.reader
->GetSize() + len
;
1949 if (ch
->load_check_proc
) {
1950 ch
->load_check_proc();
1954 if (_sl
.reader
->GetSize() != endoffs
) SlErrorCorrupt("Invalid chunk size");
1956 SlErrorCorrupt("Invalid chunk type");
1963 * Save a chunk of data (eg. vehicles, stations, etc.). Each chunk is
1964 * prefixed by an ID identifying it, followed by data, and terminator where appropriate
1965 * @param ch The chunkhandler that will be used for the operation
1967 static void SlSaveChunk(const ChunkHandler
*ch
)
1969 ChunkSaveLoadProc
*proc
= ch
->save_proc
;
1971 /* Don't save any chunk information if there is no save handler. */
1972 if (proc
== NULL
) return;
1974 SlWriteUint32(ch
->id
);
1975 DEBUG(sl
, 2, "Saving chunk %c%c%c%c", ch
->id
>> 24, ch
->id
>> 16, ch
->id
>> 8, ch
->id
);
1977 _sl
.block_mode
= ch
->flags
& CH_TYPE_MASK
;
1978 switch (ch
->flags
& CH_TYPE_MASK
) {
1980 _sl
.need_length
= NL_WANTLENGTH
;
1984 _sl
.last_array_index
= 0;
1985 SlWriteByte(CH_ARRAY
);
1987 SlWriteArrayLength(0); // Terminate arrays
1989 case CH_SPARSE_ARRAY
:
1990 SlWriteByte(CH_SPARSE_ARRAY
);
1992 SlWriteArrayLength(0); // Terminate arrays
1994 default: NOT_REACHED();
1998 /** Save all chunks */
1999 static void SlSaveChunks()
2001 FOR_ALL_CHUNK_HANDLERS(ch
) {
2010 * Find the ChunkHandler that will be used for processing the found
2011 * chunk in the savegame or in memory
2012 * @param id the chunk in question
2013 * @return returns the appropriate chunkhandler
2015 static const ChunkHandler
*SlFindChunkHandler(uint32 id
)
2017 FOR_ALL_CHUNK_HANDLERS(ch
) if (ch
->id
== id
) return ch
;
2021 /** Load all chunks */
2022 static void SlLoadChunks()
2025 const ChunkHandler
*ch
;
2027 for (id
= SlReadUint32(); id
!= 0; id
= SlReadUint32()) {
2028 DEBUG(sl
, 2, "Loading chunk %c%c%c%c", id
>> 24, id
>> 16, id
>> 8, id
);
2030 ch
= SlFindChunkHandler(id
);
2031 if (ch
== NULL
) SlErrorCorrupt("Unknown chunk type");
2036 /** Load all chunks for savegame checking */
2037 static void SlLoadCheckChunks()
2040 const ChunkHandler
*ch
;
2042 for (id
= SlReadUint32(); id
!= 0; id
= SlReadUint32()) {
2043 DEBUG(sl
, 2, "Loading chunk %c%c%c%c", id
>> 24, id
>> 16, id
>> 8, id
);
2045 ch
= SlFindChunkHandler(id
);
2046 if (ch
== NULL
) SlErrorCorrupt("Unknown chunk type");
2047 SlLoadCheckChunk(ch
);
2051 /** Fix all pointers (convert index -> pointer) */
2052 static void SlFixPointers()
2054 _sl
.action
= SLA_PTRS
;
2056 DEBUG(sl
, 1, "Fixing pointers");
2058 FOR_ALL_CHUNK_HANDLERS(ch
) {
2059 if (ch
->ptrs_proc
!= NULL
) {
2060 DEBUG(sl
, 2, "Fixing pointers for %c%c%c%c", ch
->id
>> 24, ch
->id
>> 16, ch
->id
>> 8, ch
->id
);
2065 DEBUG(sl
, 1, "All pointers fixed");
2067 assert(_sl
.action
== SLA_PTRS
);
2071 /** Yes, simply reading from a file. */
2072 struct FileReader
: LoadFilter
{
2073 FILE *file
; ///< The file to read from.
2074 long begin
; ///< The begin of the file.
2077 * Create the file reader, so it reads from a specific file.
2078 * @param file The file to read from.
2080 FileReader(FILE *file
) : LoadFilter(NULL
), file(file
), begin(ftell(file
))
2084 /** Make sure everything is cleaned up. */
2087 if (this->file
!= NULL
) fclose(this->file
);
2090 /* Make sure we don't double free. */
2094 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2096 /* We're in the process of shutting down, i.e. in "failure" mode. */
2097 if (this->file
== NULL
) return 0;
2099 return fread(buf
, 1, size
, this->file
);
2102 /* virtual */ void Reset()
2104 clearerr(this->file
);
2105 if (fseek(this->file
, this->begin
, SEEK_SET
)) {
2106 DEBUG(sl
, 1, "Could not reset the file reading");
2111 /** Yes, simply writing to a file. */
2112 struct FileWriter
: SaveFilter
{
2113 FILE *file
; ///< The file to write to.
2116 * Create the file writer, so it writes to a specific file.
2117 * @param file The file to write to.
2119 FileWriter(FILE *file
) : SaveFilter(NULL
), file(file
)
2123 /** Make sure everything is cleaned up. */
2128 /* Make sure we don't double free. */
2132 /* virtual */ void Write(byte
*buf
, size_t size
)
2134 /* We're in the process of shutting down, i.e. in "failure" mode. */
2135 if (this->file
== NULL
) return;
2137 if (fwrite(buf
, 1, size
, this->file
) != size
) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE
);
2140 /* virtual */ void Finish()
2142 if (this->file
!= NULL
) fclose(this->file
);
2147 /*******************************************
2148 ********** START OF LZO CODE **************
2149 *******************************************/
2152 #include <lzo/lzo1x.h>
2154 /** Buffer size for the LZO compressor */
2155 static const uint LZO_BUFFER_SIZE
= 8192;
2157 /** Filter using LZO compression. */
2158 struct LZOLoadFilter
: LoadFilter
{
2160 * Initialise this filter.
2161 * @param chain The next filter in this chain.
2163 LZOLoadFilter(LoadFilter
*chain
) : LoadFilter(chain
)
2165 if (lzo_init() != LZO_E_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize decompressor");
2168 /* virtual */ size_t Read(byte
*buf
, size_t ssize
)
2170 assert(ssize
>= LZO_BUFFER_SIZE
);
2172 /* Buffer size is from the LZO docs plus the chunk header size. */
2173 byte out
[LZO_BUFFER_SIZE
+ LZO_BUFFER_SIZE
/ 16 + 64 + 3 + sizeof(uint32
) * 2];
2176 lzo_uint len
= ssize
;
2179 if (this->chain
->Read((byte
*)tmp
, sizeof(tmp
)) != sizeof(tmp
)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
, "File read failed");
2181 /* Check if size is bad */
2182 ((uint32
*)out
)[0] = size
= tmp
[1];
2184 if (_sl_version
!= 0) {
2185 tmp
[0] = TO_BE32(tmp
[0]);
2186 size
= TO_BE32(size
);
2189 if (size
>= sizeof(out
)) SlErrorCorrupt("Inconsistent size");
2192 if (this->chain
->Read(out
+ sizeof(uint32
), size
) != size
) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
2194 /* Verify checksum */
2195 if (tmp
[0] != lzo_adler32(0, out
, size
+ sizeof(uint32
))) SlErrorCorrupt("Bad checksum");
2198 int ret
= lzo1x_decompress_safe(out
+ sizeof(uint32
) * 1, size
, buf
, &len
, NULL
);
2199 if (ret
!= LZO_E_OK
) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
2204 /** Filter using LZO compression. */
2205 struct LZOSaveFilter
: SaveFilter
{
2207 * Initialise this filter.
2208 * @param chain The next filter in this chain.
2209 * @param compression_level The requested level of compression.
2211 LZOSaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
)
2213 if (lzo_init() != LZO_E_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize compressor");
2216 /* virtual */ void Write(byte
*buf
, size_t size
)
2218 const lzo_bytep in
= buf
;
2219 /* Buffer size is from the LZO docs plus the chunk header size. */
2220 byte out
[LZO_BUFFER_SIZE
+ LZO_BUFFER_SIZE
/ 16 + 64 + 3 + sizeof(uint32
) * 2];
2221 byte wrkmem
[LZO1X_1_MEM_COMPRESS
];
2225 /* Compress up to LZO_BUFFER_SIZE bytes at once. */
2226 lzo_uint len
= size
> LZO_BUFFER_SIZE
? LZO_BUFFER_SIZE
: (lzo_uint
)size
;
2227 lzo1x_1_compress(in
, len
, out
+ sizeof(uint32
) * 2, &outlen
, wrkmem
);
2228 ((uint32
*)out
)[1] = TO_BE32((uint32
)outlen
);
2229 ((uint32
*)out
)[0] = TO_BE32(lzo_adler32(0, out
+ sizeof(uint32
), outlen
+ sizeof(uint32
)));
2230 this->chain
->Write(out
, outlen
+ sizeof(uint32
) * 2);
2232 /* Move to next data chunk. */
2239 #endif /* WITH_LZO */
2241 /*********************************************
2242 ******** START OF NOCOMP CODE (uncompressed)*
2243 *********************************************/
2245 /** Filter without any compression. */
2246 struct NoCompLoadFilter
: LoadFilter
{
2248 * Initialise this filter.
2249 * @param chain The next filter in this chain.
2251 NoCompLoadFilter(LoadFilter
*chain
) : LoadFilter(chain
)
2255 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2257 return this->chain
->Read(buf
, size
);
2261 /** Filter without any compression. */
2262 struct NoCompSaveFilter
: SaveFilter
{
2264 * Initialise this filter.
2265 * @param chain The next filter in this chain.
2266 * @param compression_level The requested level of compression.
2268 NoCompSaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
)
2272 /* virtual */ void Write(byte
*buf
, size_t size
)
2274 this->chain
->Write(buf
, size
);
2278 /********************************************
2279 ********** START OF ZLIB CODE **************
2280 ********************************************/
2282 #if defined(WITH_ZLIB)
2285 /** Filter using Zlib compression. */
2286 struct ZlibLoadFilter
: LoadFilter
{
2287 z_stream z
; ///< Stream state we are reading from.
2288 byte fread_buf
[MEMORY_CHUNK_SIZE
]; ///< Buffer for reading from the file.
2291 * Initialise this filter.
2292 * @param chain The next filter in this chain.
2294 ZlibLoadFilter(LoadFilter
*chain
) : LoadFilter(chain
)
2296 memset(&this->z
, 0, sizeof(this->z
));
2297 if (inflateInit(&this->z
) != Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize decompressor");
2300 /** Clean everything up. */
2303 inflateEnd(&this->z
);
2306 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2308 this->z
.next_out
= buf
;
2309 this->z
.avail_out
= (uint
)size
;
2312 /* read more bytes from the file? */
2313 if (this->z
.avail_in
== 0) {
2314 this->z
.next_in
= this->fread_buf
;
2315 this->z
.avail_in
= (uint
)this->chain
->Read(this->fread_buf
, sizeof(this->fread_buf
));
2318 /* inflate the data */
2319 int r
= inflate(&this->z
, 0);
2320 if (r
== Z_STREAM_END
) break;
2322 if (r
!= Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "inflate() failed");
2323 } while (this->z
.avail_out
!= 0);
2325 return size
- this->z
.avail_out
;
2329 /** Filter using Zlib compression. */
2330 struct ZlibSaveFilter
: SaveFilter
{
2331 z_stream z
; ///< Stream state we are writing to.
2334 * Initialise this filter.
2335 * @param chain The next filter in this chain.
2336 * @param compression_level The requested level of compression.
2338 ZlibSaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
)
2340 memset(&this->z
, 0, sizeof(this->z
));
2341 if (deflateInit(&this->z
, compression_level
) != Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize compressor");
2344 /** Clean up what we allocated. */
2347 deflateEnd(&this->z
);
2351 * Helper loop for writing the data.
2352 * @param p The bytes to write.
2353 * @param len Amount of bytes to write.
2354 * @param mode Mode for deflate.
2356 void WriteLoop(byte
*p
, size_t len
, int mode
)
2358 byte buf
[MEMORY_CHUNK_SIZE
]; // output buffer
2360 this->z
.next_in
= p
;
2361 this->z
.avail_in
= (uInt
)len
;
2363 this->z
.next_out
= buf
;
2364 this->z
.avail_out
= sizeof(buf
);
2367 * For the poor next soul who sees many valgrind warnings of the
2368 * "Conditional jump or move depends on uninitialised value(s)" kind:
2369 * According to the author of zlib it is not a bug and it won't be fixed.
2370 * http://groups.google.com/group/comp.compression/browse_thread/thread/b154b8def8c2a3ef/cdf9b8729ce17ee2
2371 * [Mark Adler, Feb 24 2004, 'zlib-1.2.1 valgrind warnings' in the newsgroup comp.compression]
2373 int r
= deflate(&this->z
, mode
);
2375 /* bytes were emitted? */
2376 if ((n
= sizeof(buf
) - this->z
.avail_out
) != 0) {
2377 this->chain
->Write(buf
, n
);
2379 if (r
== Z_STREAM_END
) break;
2381 if (r
!= Z_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "zlib returned error code");
2382 } while (this->z
.avail_in
|| !this->z
.avail_out
);
2385 /* virtual */ void Write(byte
*buf
, size_t size
)
2387 this->WriteLoop(buf
, size
, 0);
2390 /* virtual */ void Finish()
2392 this->WriteLoop(NULL
, 0, Z_FINISH
);
2393 this->chain
->Finish();
2397 #endif /* WITH_ZLIB */
2399 /********************************************
2400 ********** START OF LZMA CODE **************
2401 ********************************************/
2403 #if defined(WITH_LZMA)
2407 * Have a copy of an initialised LZMA stream. We need this as it's
2408 * impossible to "re"-assign LZMA_STREAM_INIT to a variable in some
2409 * compilers, i.e. LZMA_STREAM_INIT can't be used to set something.
2410 * This var has to be used instead.
2412 static const lzma_stream _lzma_init
= LZMA_STREAM_INIT
;
2414 /** Filter without any compression. */
2415 struct LZMALoadFilter
: LoadFilter
{
2416 lzma_stream lzma
; ///< Stream state that we are reading from.
2417 byte fread_buf
[MEMORY_CHUNK_SIZE
]; ///< Buffer for reading from the file.
2420 * Initialise this filter.
2421 * @param chain The next filter in this chain.
2423 LZMALoadFilter(LoadFilter
*chain
) : LoadFilter(chain
), lzma(_lzma_init
)
2425 /* Allow saves up to 256 MB uncompressed */
2426 if (lzma_auto_decoder(&this->lzma
, 1 << 28, 0) != LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize decompressor");
2429 /** Clean everything up. */
2432 lzma_end(&this->lzma
);
2435 /* virtual */ size_t Read(byte
*buf
, size_t size
)
2437 this->lzma
.next_out
= buf
;
2438 this->lzma
.avail_out
= size
;
2441 /* read more bytes from the file? */
2442 if (this->lzma
.avail_in
== 0) {
2443 this->lzma
.next_in
= this->fread_buf
;
2444 this->lzma
.avail_in
= this->chain
->Read(this->fread_buf
, sizeof(this->fread_buf
));
2447 /* inflate the data */
2448 lzma_ret r
= lzma_code(&this->lzma
, LZMA_RUN
);
2449 if (r
== LZMA_STREAM_END
) break;
2450 if (r
!= LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "liblzma returned error code");
2451 } while (this->lzma
.avail_out
!= 0);
2453 return size
- this->lzma
.avail_out
;
2457 /** Filter using LZMA compression. */
2458 struct LZMASaveFilter
: SaveFilter
{
2459 lzma_stream lzma
; ///< Stream state that we are writing to.
2462 * Initialise this filter.
2463 * @param chain The next filter in this chain.
2464 * @param compression_level The requested level of compression.
2466 LZMASaveFilter(SaveFilter
*chain
, byte compression_level
) : SaveFilter(chain
), lzma(_lzma_init
)
2468 if (lzma_easy_encoder(&this->lzma
, compression_level
, LZMA_CHECK_CRC32
) != LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "cannot initialize compressor");
2471 /** Clean up what we allocated. */
2474 lzma_end(&this->lzma
);
2478 * Helper loop for writing the data.
2479 * @param p The bytes to write.
2480 * @param len Amount of bytes to write.
2481 * @param action Action for lzma_code.
2483 void WriteLoop(byte
*p
, size_t len
, lzma_action action
)
2485 byte buf
[MEMORY_CHUNK_SIZE
]; // output buffer
2487 this->lzma
.next_in
= p
;
2488 this->lzma
.avail_in
= len
;
2490 this->lzma
.next_out
= buf
;
2491 this->lzma
.avail_out
= sizeof(buf
);
2493 lzma_ret r
= lzma_code(&this->lzma
, action
);
2495 /* bytes were emitted? */
2496 if ((n
= sizeof(buf
) - this->lzma
.avail_out
) != 0) {
2497 this->chain
->Write(buf
, n
);
2499 if (r
== LZMA_STREAM_END
) break;
2500 if (r
!= LZMA_OK
) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, "liblzma returned error code");
2501 } while (this->lzma
.avail_in
|| !this->lzma
.avail_out
);
2504 /* virtual */ void Write(byte
*buf
, size_t size
)
2506 this->WriteLoop(buf
, size
, LZMA_RUN
);
2509 /* virtual */ void Finish()
2511 this->WriteLoop(NULL
, 0, LZMA_FINISH
);
2512 this->chain
->Finish();
2516 #endif /* WITH_LZMA */
2518 /*******************************************
2519 ************* END OF CODE *****************
2520 *******************************************/
2522 /** The format for a reader/writer type of a savegame */
2523 struct SaveLoadFormat
{
2524 const char *name
; ///< name of the compressor/decompressor (debug-only)
2525 uint32 tag
; ///< the 4-letter tag by which it is identified in the savegame
2527 LoadFilter
*(*init_load
)(LoadFilter
*chain
); ///< Constructor for the load filter.
2528 SaveFilter
*(*init_write
)(SaveFilter
*chain
, byte compression
); ///< Constructor for the save filter.
2530 byte min_compression
; ///< the minimum compression level of this format
2531 byte default_compression
; ///< the default compression level of this format
2532 byte max_compression
; ///< the maximum compression level of this format
2535 /** The different saveload formats known/understood by OpenTTD. */
2536 static const SaveLoadFormat _saveload_formats
[] = {
2537 #if defined(WITH_LZO)
2538 /* Roughly 75% larger than zlib level 6 at only ~7% of the CPU usage. */
2539 {"lzo", TO_BE32X('OTTD'), CreateLoadFilter
<LZOLoadFilter
>, CreateSaveFilter
<LZOSaveFilter
>, 0, 0, 0},
2541 {"lzo", TO_BE32X('OTTD'), NULL
, NULL
, 0, 0, 0},
2543 /* Roughly 5 times larger at only 1% of the CPU usage over zlib level 6. */
2544 {"none", TO_BE32X('OTTN'), CreateLoadFilter
<NoCompLoadFilter
>, CreateSaveFilter
<NoCompSaveFilter
>, 0, 0, 0},
2545 #if defined(WITH_ZLIB)
2546 /* After level 6 the speed reduction is significant (1.5x to 2.5x slower per level), but the reduction in filesize is
2547 * fairly insignificant (~1% for each step). Lower levels become ~5-10% bigger by each level than level 6 while level
2548 * 1 is "only" 3 times as fast. Level 0 results in uncompressed savegames at about 8 times the cost of "none". */
2549 {"zlib", TO_BE32X('OTTZ'), CreateLoadFilter
<ZlibLoadFilter
>, CreateSaveFilter
<ZlibSaveFilter
>, 0, 6, 9},
2551 {"zlib", TO_BE32X('OTTZ'), NULL
, NULL
, 0, 0, 0},
2553 #if defined(WITH_LZMA)
2554 /* Level 2 compression is speed wise as fast as zlib level 6 compression (old default), but results in ~10% smaller saves.
2555 * Higher compression levels are possible, and might improve savegame size by up to 25%, but are also up to 10 times slower.
2556 * The next significant reduction in file size is at level 4, but that is already 4 times slower. Level 3 is primarily 50%
2557 * slower while not improving the filesize, while level 0 and 1 are faster, but don't reduce savegame size much.
2558 * It's OTTX and not e.g. OTTL because liblzma is part of xz-utils and .tar.xz is preferred over .tar.lzma. */
2559 {"lzma", TO_BE32X('OTTX'), CreateLoadFilter
<LZMALoadFilter
>, CreateSaveFilter
<LZMASaveFilter
>, 0, 2, 9},
2561 {"lzma", TO_BE32X('OTTX'), NULL
, NULL
, 0, 0, 0},
2566 * Return the savegameformat of the game. Whether it was created with ZLIB compression
2567 * uncompressed, or another type
2568 * @param s Name of the savegame format. If NULL it picks the first available one
2569 * @param compression_level Output for telling what compression level we want.
2570 * @return Pointer to SaveLoadFormat struct giving all characteristics of this type of savegame
2572 static const SaveLoadFormat
*GetSavegameFormat(char *s
, byte
*compression_level
)
2574 const SaveLoadFormat
*def
= lastof(_saveload_formats
);
2576 /* find default savegame format, the highest one with which files can be written */
2577 while (!def
->init_write
) def
--;
2580 /* Get the ":..." of the compression level out of the way */
2581 char *complevel
= strrchr(s
, ':');
2582 if (complevel
!= NULL
) *complevel
= '\0';
2584 for (const SaveLoadFormat
*slf
= &_saveload_formats
[0]; slf
!= endof(_saveload_formats
); slf
++) {
2585 if (slf
->init_write
!= NULL
&& strcmp(s
, slf
->name
) == 0) {
2586 *compression_level
= slf
->default_compression
;
2587 if (complevel
!= NULL
) {
2588 /* There is a compression level in the string.
2589 * First restore the : we removed to do proper name matching,
2590 * then move the the begin of the actual version. */
2594 /* Get the version and determine whether all went fine. */
2596 long level
= strtol(complevel
, &end
, 10);
2597 if (end
== complevel
|| level
!= Clamp(level
, slf
->min_compression
, slf
->max_compression
)) {
2598 SetDParamStr(0, complevel
);
2599 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_LEVEL
, WL_CRITICAL
);
2601 *compression_level
= level
;
2609 SetDParamStr(1, def
->name
);
2610 ShowErrorMessage(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_SAVEGAME_COMPRESSION_ALGORITHM
, WL_CRITICAL
);
2612 /* Restore the string by adding the : back */
2613 if (complevel
!= NULL
) *complevel
= ':';
2615 *compression_level
= def
->default_compression
;
2619 /* actual loader/saver function */
2620 void InitializeGame(uint size_x
, uint size_y
, bool reset_date
, bool reset_settings
);
2621 extern bool AfterLoadGame();
2622 extern bool LoadOldSaveGame(const char *file
);
2625 * Clear/free saveload state.
2627 static inline void ClearSaveLoadState()
2643 * Update the gui accordingly when starting saving
2644 * and set locks on saveload. Also turn off fast-forward cause with that
2645 * saving takes Aaaaages
2647 static void SaveFileStart()
2649 _sl
.ff_state
= _fast_forward
;
2651 SetMouseCursorBusy(true);
2653 InvalidateWindowData(WC_STATUS_BAR
, 0, SBI_SAVELOAD_START
);
2654 _sl
.saveinprogress
= true;
2657 /** Update the gui accordingly when saving is done and release locks on saveload. */
2658 static void SaveFileDone()
2660 if (_game_mode
!= GM_MENU
) _fast_forward
= _sl
.ff_state
;
2661 SetMouseCursorBusy(false);
2663 InvalidateWindowData(WC_STATUS_BAR
, 0, SBI_SAVELOAD_FINISH
);
2664 _sl
.saveinprogress
= false;
2667 /** Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friends) */
2668 void SetSaveLoadError(StringID str
)
2670 _sl
.error_str
= str
;
2673 /** Get the string representation of the error message */
2674 const char *GetSaveLoadErrorString()
2676 SetDParam(0, _sl
.error_str
);
2677 SetDParamStr(1, _sl
.extra_msg
);
2679 static char err_str
[512];
2680 GetString(err_str
, _sl
.action
== SLA_SAVE
? STR_ERROR_GAME_SAVE_FAILED
: STR_ERROR_GAME_LOAD_FAILED
, lastof(err_str
));
2684 /** Show a gui message when saving has failed */
2685 static void SaveFileError()
2687 SetDParamStr(0, GetSaveLoadErrorString());
2688 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
2693 * We have written the whole game into memory, _memory_savegame, now find
2694 * and appropriate compressor and start writing to file.
2696 static SaveOrLoadResult
SaveFileToDisk(bool threaded
)
2700 const SaveLoadFormat
*fmt
= GetSavegameFormat(_savegame_format
, &compression
);
2702 /* We have written our stuff to memory, now write it to file! */
2703 uint32 hdr
[2] = { fmt
->tag
, TO_BE32(SAVEGAME_VERSION
<< 16) };
2704 _sl
.sf
->Write((byte
*)hdr
, sizeof(hdr
));
2706 _sl
.sf
= fmt
->init_write(_sl
.sf
, compression
);
2707 _sl
.dumper
->Flush(_sl
.sf
);
2709 ClearSaveLoadState();
2711 if (threaded
) SetAsyncSaveFinish(SaveFileDone
);
2715 ClearSaveLoadState();
2717 AsyncSaveFinishProc asfp
= SaveFileDone
;
2719 /* We don't want to shout when saving is just
2720 * cancelled due to a client disconnecting. */
2721 if (_sl
.error_str
!= STR_NETWORK_ERROR_LOSTCONNECTION
) {
2722 /* Skip the "colour" character */
2723 DEBUG(sl
, 0, "%s", GetSaveLoadErrorString() + 3);
2724 asfp
= SaveFileError
;
2728 SetAsyncSaveFinish(asfp
);
2736 /** Thread run function for saving the file to disk. */
2737 static void SaveFileToDiskThread(void *arg
)
2739 SaveFileToDisk(true);
2742 void WaitTillSaved()
2744 if (_save_thread
== NULL
) return;
2746 _save_thread
->Join();
2747 delete _save_thread
;
2748 _save_thread
= NULL
;
2750 /* Make sure every other state is handled properly as well. */
2751 ProcessAsyncSaveFinish();
2755 * Actually perform the saving of the savegame.
2756 * General tactics is to first save the game to memory, then write it to file
2757 * using the writer, either in threaded mode if possible, or single-threaded.
2758 * @param writer The filter to write the savegame to.
2759 * @param threaded Whether to try to perform the saving asynchronously.
2760 * @return Return the result of the action. #SL_OK or #SL_ERROR
2762 static SaveOrLoadResult
DoSave(SaveFilter
*writer
, bool threaded
)
2764 assert(!_sl
.saveinprogress
);
2766 _sl
.dumper
= new MemoryDumper();
2769 _sl_version
= SAVEGAME_VERSION
;
2771 SaveViewportBeforeSaveGame();
2775 if (!threaded
|| !ThreadObject::New(&SaveFileToDiskThread
, NULL
, &_save_thread
, "ottd:savegame")) {
2776 if (threaded
) DEBUG(sl
, 1, "Cannot create savegame thread, reverting to single-threaded mode...");
2778 SaveOrLoadResult result
= SaveFileToDisk(false);
2788 * Save the game using a (writer) filter.
2789 * @param writer The filter to write the savegame to.
2790 * @param threaded Whether to try to perform the saving asynchronously.
2791 * @return Return the result of the action. #SL_OK or #SL_ERROR
2793 SaveOrLoadResult
SaveWithFilter(SaveFilter
*writer
, bool threaded
)
2796 _sl
.action
= SLA_SAVE
;
2797 return DoSave(writer
, threaded
);
2799 ClearSaveLoadState();
2805 * Actually perform the loading of a "non-old" savegame.
2806 * @param reader The filter to read the savegame from.
2807 * @param load_check Whether to perform the checking ("preview") or actually load the game.
2808 * @return Return the result of the action. #SL_OK or #SL_REINIT ("unload" the game)
2810 static SaveOrLoadResult
DoLoad(LoadFilter
*reader
, bool load_check
)
2815 /* Clear previous check data */
2816 _load_check_data
.Clear();
2817 /* Mark SL_LOAD_CHECK as supported for this savegame. */
2818 _load_check_data
.checkable
= true;
2822 if (_sl
.lf
->Read((byte
*)hdr
, sizeof(hdr
)) != sizeof(hdr
)) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
2824 /* see if we have any loader for this type. */
2825 const SaveLoadFormat
*fmt
= _saveload_formats
;
2827 /* No loader found, treat as version 0 and use LZO format */
2828 if (fmt
== endof(_saveload_formats
)) {
2829 DEBUG(sl
, 0, "Unknown savegame type, trying to load it as the buggy format");
2832 _sl_minor_version
= 0;
2834 /* Try to find the LZO savegame format; it uses 'OTTD' as tag. */
2835 fmt
= _saveload_formats
;
2837 if (fmt
== endof(_saveload_formats
)) {
2838 /* Who removed LZO support? Bad bad boy! */
2841 if (fmt
->tag
== TO_BE32X('OTTD')) break;
2847 if (fmt
->tag
== hdr
[0]) {
2848 /* check version number */
2849 _sl_version
= TO_BE32(hdr
[1]) >> 16;
2850 /* Minor is not used anymore from version 18.0, but it is still needed
2851 * in versions before that (4 cases) which can't be removed easy.
2852 * Therefore it is loaded, but never saved (or, it saves a 0 in any scenario). */
2853 _sl_minor_version
= (TO_BE32(hdr
[1]) >> 8) & 0xFF;
2855 DEBUG(sl
, 1, "Loading savegame version %d", _sl_version
);
2857 /* Is the version higher than the current? */
2858 if (_sl_version
> SAVEGAME_VERSION
) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME
);
2865 /* loader for this savegame type is not implemented? */
2866 if (fmt
->init_load
== NULL
) {
2868 seprintf(err_str
, lastof(err_str
), "Loader for '%s' is not available.", fmt
->name
);
2869 SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR
, err_str
);
2872 _sl
.lf
= fmt
->init_load(_sl
.lf
);
2873 _sl
.reader
= new ReadBuffer(_sl
.lf
);
2877 /* Old maps were hardcoded to 256x256 and thus did not contain
2878 * any mapsize information. Pre-initialize to 256x256 to not to
2879 * confuse old games */
2880 InitializeGame(256, 256, true, true);
2884 if (IsSavegameVersionBefore(4)) {
2886 * NewGRFs were introduced between 0.3,4 and 0.3.5, which both
2887 * shared savegame version 4. Anything before that 'obviously'
2888 * does not have any NewGRFs. Between the introduction and
2889 * savegame version 41 (just before 0.5) the NewGRF settings
2890 * were not stored in the savegame and they were loaded by
2891 * using the settings from the main menu.
2893 * - savegame version < 4: do not load any NewGRFs.
2894 * - savegame version >= 41: load NewGRFs from savegame, which is
2895 * already done at this stage by
2896 * overwriting the main menu settings.
2897 * - other savegame versions: use main menu settings.
2899 * This means that users *can* crash savegame version 4..40
2900 * savegames if they set incompatible NewGRFs in the main menu,
2901 * but can't crash anymore for savegame version < 4 savegames.
2903 * Note: this is done here because AfterLoadGame is also called
2904 * for TTO/TTD/TTDP savegames which have their own NewGRF logic.
2906 ClearGRFConfigList(&_grfconfig
);
2911 /* Load chunks into _load_check_data.
2912 * No pools are loaded. References are not possible, and thus do not need resolving. */
2913 SlLoadCheckChunks();
2915 /* Load chunks and resolve references */
2920 ClearSaveLoadState();
2922 _savegame_type
= SGT_OTTD
;
2925 /* The only part from AfterLoadGame() we need */
2926 _load_check_data
.grf_compatibility
= IsGoodGRFConfigList(_load_check_data
.grfconfig
);
2928 GamelogStartAction(GLAT_LOAD
);
2930 /* After loading fix up savegame for any internal changes that
2931 * might have occurred since then. If it fails, load back the old game. */
2932 if (!AfterLoadGame()) {
2933 GamelogStopAction();
2937 GamelogStopAction();
2944 * Load the game using a (reader) filter.
2945 * @param reader The filter to read the savegame from.
2946 * @return Return the result of the action. #SL_OK or #SL_REINIT ("unload" the game)
2948 SaveOrLoadResult
LoadWithFilter(LoadFilter
*reader
)
2951 _sl
.action
= SLA_LOAD
;
2952 return DoLoad(reader
, false);
2954 ClearSaveLoadState();
2960 * Main Save or Load function where the high-level saveload functions are
2961 * handled. It opens the savegame, selects format and checks versions
2962 * @param filename The name of the savegame being created/loaded
2963 * @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.
2964 * @param sb The sub directory to save the savegame in
2965 * @param threaded True when threaded saving is allowed
2966 * @return Return the result of the action. #SL_OK, #SL_ERROR, or #SL_REINIT ("unload" the game)
2968 SaveOrLoadResult
SaveOrLoad(const char *filename
, SaveLoadOperation fop
, DetailedFileType dft
, Subdirectory sb
, bool threaded
)
2970 /* An instance of saving is already active, so don't go saving again */
2971 if (_sl
.saveinprogress
&& fop
== SLO_SAVE
&& dft
== DFT_GAME_FILE
&& threaded
) {
2972 /* if not an autosave, but a user action, show error message */
2973 if (!_do_autosave
) ShowErrorMessage(STR_ERROR_SAVE_STILL_IN_PROGRESS
, INVALID_STRING_ID
, WL_ERROR
);
2979 /* Load a TTDLX or TTDPatch game */
2980 if (fop
== SLO_LOAD
&& dft
== DFT_OLD_GAME_FILE
) {
2981 InitializeGame(256, 256, true, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
2983 /* TTD/TTO savegames have no NewGRFs, TTDP savegame have them
2984 * and if so a new NewGRF list will be made in LoadOldSaveGame.
2985 * Note: this is done here because AfterLoadGame is also called
2986 * for OTTD savegames which have their own NewGRF logic. */
2987 ClearGRFConfigList(&_grfconfig
);
2989 if (!LoadOldSaveGame(filename
)) return SL_REINIT
;
2991 _sl_minor_version
= 0;
2992 GamelogStartAction(GLAT_LOAD
);
2993 if (!AfterLoadGame()) {
2994 GamelogStopAction();
2997 GamelogStopAction();
3001 assert(dft
== DFT_GAME_FILE
);
3004 _sl
.action
= SLA_LOAD_CHECK
;
3008 _sl
.action
= SLA_LOAD
;
3012 _sl
.action
= SLA_SAVE
;
3015 default: NOT_REACHED();
3018 FILE *fh
= (fop
== SLO_SAVE
) ? FioFOpenFile(filename
, "wb", sb
) : FioFOpenFile(filename
, "rb", sb
);
3020 /* Make it a little easier to load savegames from the console */
3021 if (fh
== NULL
&& fop
!= SLO_SAVE
) fh
= FioFOpenFile(filename
, "rb", SAVE_DIR
);
3022 if (fh
== NULL
&& fop
!= SLO_SAVE
) fh
= FioFOpenFile(filename
, "rb", BASE_DIR
);
3023 if (fh
== NULL
&& fop
!= SLO_SAVE
) fh
= FioFOpenFile(filename
, "rb", SCENARIO_DIR
);
3026 SlError(fop
== SLO_SAVE
? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE
: STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE
);
3029 if (fop
== SLO_SAVE
) { // SAVE game
3030 DEBUG(desync
, 1, "save: %08x; %02x; %s", _date
, _date_fract
, filename
);
3031 if (_network_server
|| !_settings_client
.gui
.threaded_saves
) threaded
= false;
3033 return DoSave(new FileWriter(fh
), threaded
);
3037 assert(fop
== SLO_LOAD
|| fop
== SLO_CHECK
);
3038 DEBUG(desync
, 1, "load: %s", filename
);
3039 return DoLoad(new FileReader(fh
), fop
== SLO_CHECK
);
3041 /* This code may be executed both for old and new save games. */
3042 ClearSaveLoadState();
3044 /* Skip the "colour" character */
3045 if (fop
!= SLO_CHECK
) DEBUG(sl
, 0, "%s", GetSaveLoadErrorString() + 3);
3047 /* A saver/loader exception!! reinitialize all variables to prevent crash! */
3048 return (fop
== SLO_LOAD
) ? SL_REINIT
: SL_ERROR
;
3052 /** Do a save when exiting the game (_settings_client.gui.autosave_on_exit) */
3055 SaveOrLoad("exit.sav", SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
);
3059 * Fill the buffer with the default name for a savegame *or* screenshot.
3060 * @param buf the buffer to write to.
3061 * @param last the last element in the buffer.
3063 void GenerateDefaultSaveName(char *buf
, const char *last
)
3065 /* Check if we have a name for this map, which is the name of the first
3066 * available company. When there's no company available we'll use
3067 * 'Spectator' as "company" name. */
3068 CompanyID cid
= _local_company
;
3069 if (!Company::IsValidID(cid
)) {
3071 FOR_ALL_COMPANIES(c
) {
3079 /* Insert current date */
3080 switch (_settings_client
.gui
.date_format_in_default_names
) {
3081 case 0: SetDParam(1, STR_JUST_DATE_LONG
); break;
3082 case 1: SetDParam(1, STR_JUST_DATE
); break;
3083 case 2: SetDParam(1, STR_JUST_DATE_ISO
); break;
3084 default: NOT_REACHED();
3086 SetDParam(2, _date
);
3088 /* Get the correct string (special string for when there's not company) */
3089 GetString(buf
, !Company::IsValidID(cid
) ? STR_SAVEGAME_NAME_SPECTATOR
: STR_SAVEGAME_NAME_DEFAULT
, last
);
3090 SanitizeFilename(buf
);
3094 * Set the mode and file type of the file to save or load based on the type of file entry at the file system.
3095 * @param ft Type of file entry of the file system.
3097 void FileToSaveLoad::SetMode(FiosType ft
)
3099 this->SetMode(SLO_LOAD
, GetAbstractFileType(ft
), GetDetailedFileType(ft
));
3103 * Set the mode and file type of the file to save or load.
3104 * @param fop File operation being performed.
3105 * @param aft Abstract file type.
3106 * @param dft Detailed file type.
3108 void FileToSaveLoad::SetMode(SaveLoadOperation fop
, AbstractFileType aft
, DetailedFileType dft
)
3110 if (aft
== FT_INVALID
|| aft
== FT_NONE
) {
3111 this->file_op
= SLO_INVALID
;
3112 this->detail_ftype
= DFT_INVALID
;
3113 this->abstract_ftype
= FT_INVALID
;
3117 this->file_op
= fop
;
3118 this->detail_ftype
= dft
;
3119 this->abstract_ftype
= aft
;
3123 * Set the name of the file.
3124 * @param name Name of the file.
3126 void FileToSaveLoad::SetName(const char *name
)
3128 strecpy(this->name
, name
, lastof(this->name
));
3132 * Set the title of the file.
3133 * @param title Title of the file.
3135 void FileToSaveLoad::SetTitle(const char *title
)
3137 strecpy(this->title
, title
, lastof(this->title
));
3142 * Function to get the type of the savegame by looking at the file header.
3143 * NOTICE: Not used right now, but could be used if extensions of savegames are garbled
3144 * @param file Savegame to be checked
3145 * @return SL_OLD_LOAD or SL_LOAD of the file
3147 int GetSavegameType(char *file
)
3149 const SaveLoadFormat
*fmt
;
3152 int mode
= SL_OLD_LOAD
;
3154 f
= fopen(file
, "rb");
3155 if (fread(&hdr
, sizeof(hdr
), 1, f
) != 1) {
3156 DEBUG(sl
, 0, "Savegame is obsolete or invalid format");
3157 mode
= SL_LOAD
; // don't try to get filename, just show name as it is written
3159 /* see if we have any loader for this type. */
3160 for (fmt
= _saveload_formats
; fmt
!= endof(_saveload_formats
); fmt
++) {
3161 if (fmt
->tag
== hdr
) {
3162 mode
= SL_LOAD
; // new type of savegame