# saveload.cpp File Reference

All actions handling saving and loading goes on in this file. More...

`#include "../stdafx.h"`
`#include "../debug.h"`
`#include "../station_base.h"`
`#include "../thread/thread.h"`
`#include "../town.h"`
`#include "../network/network.h"`
`#include "../variables.h"`
`#include "../window_func.h"`
`#include "../strings_func.h"`
`#include "../core/endian_func.hpp"`
`#include "../vehicle_base.h"`
`#include "../company_func.h"`
`#include "../date_func.h"`
`#include "../autoreplace_base.h"`
`#include "../roadstop_base.h"`
`#include "../statusbar_gui.h"`
`#include "../fileio_func.h"`
`#include "../gamelog.h"`
`#include "../string_func.h"`
`#include "../engine_base.h"`
`#include "../company_base.h"`
`#include "table/strings.h"`
`#include "saveload_internal.h"`
`#include "../gui.h"`

Go to the source code of this file.

## Data Structures
struct | SaveLoadParams
| The saveload struct, containing reader-writer functions, bufffer, version, etc. More...
struct | ThreadedSave
struct | SaveLoadFormat
| The format for a reader/writer type of a savegame. More...
## Defines
#define | FOR_ALL_CHUNK_HANDLERS(ch)
| Iterate over all chunk handlers.
## Typedefs
typedef void | WriterProc (size_t len)
typedef size_t | ReaderProc ()
typedef void(* | AsyncSaveFinishProc )()
## Enumerations
enum | SaveLoadAction { SLA_LOAD, SLA_SAVE, SLA_PTRS, SLA_NULL }
| What are we currently doing? More...
enum | NeedLength { NL_NONE = 0, NL_WANTLENGTH = 1, NL_CALCLENGTH = 2 }
## Functions
static void | SlNullPointers ()
| Null all pointers (convert index -> NULL).
static void NORETURN | SlError (StringID string, const char *extra_msg=NULL)
| Error handler, calls longjmp to simulate an exception.
static void | SetAsyncSaveFinish (AsyncSaveFinishProc proc)
| Called by save thread to tell we finished saving.
void | ProcessAsyncSaveFinish ()
| Handle async save finishes.
static void | SlReadFill ()
| Fill the input buffer by reading from the file with the given reader.
static size_t | SlGetOffs ()
static uint | SlReadArrayLength ()
static uint | SlCalcConvMemLen (VarType conv)
| Return the size in bytes of a certain type of normal/atomic variable as it appears in memory.
static byte | SlCalcConvFileLen (VarType conv)
| Return the size in bytes of a certain type of normal/atomic variable as it appears in a saved game.
static size_t | SlCalcRefLen ()
| Return the size in bytes of a reference (pointer).
static void | SlWriteFill ()
| Flush the output buffer by writing to disk with the given reader.
static byte | SlReadByteInternal ()
| Read in a single byte from file.
byte | SlReadByte ()
| Wrapper for SlReadByteInternal.
static void | SlWriteByteInternal (byte b)
| Write away a single byte from memory.
void | SlWriteByte (byte b)
| Wrapper for SlWriteByteInternal.
static int | SlReadUint16 ()
static uint32 | SlReadUint32 ()
static uint64 | SlReadUint64 ()
static void | SlWriteUint16 (uint16 v)
static void | SlWriteUint32 (uint32 v)
static void | SlWriteUint64 (uint64 x)
static uint | SlReadSimpleGamma ()
| Read in the header descriptor of an object or an array.
static void | SlWriteSimpleGamma (size_t i)
| Write the header descriptor of an object or an array.
static uint | SlGetGammaLength (size_t i)
| Return how many bytes used to encode a gamma value.
static uint | SlReadSparseIndex ()
static void | SlWriteSparseIndex (uint index)
static void | SlWriteArrayLength (size_t length)
static uint | SlGetArrayLength (size_t length)
void | SlSetArrayIndex (uint index)
int | SlIterateArray ()
| Iterate through the elements of an array and read the whole thing.
void | SlSetLength (size_t length)
| Sets the length of either a RIFF object or the number of items in an array.
static void | SlCopyBytes (void *ptr, size_t length)
| Save/Load bytes.
static void | SlSkipBytes (size_t length)
| Read in bytes from the file/data structure but don't do anything with them, discarding them in effect.
size_t | SlGetFieldLength ()
int64 | ReadValue (const void *ptr, VarType conv)
| Return a signed-long version of the value of a setting.
void | WriteValue (void *ptr, VarType conv, int64 val)
| Write the value of a setting.
static void | SlSaveLoadConv (void *ptr, VarType conv)
| Handle all conversion and typechecking of variables here.
static size_t | SlCalcNetStringLen (const char *ptr, size_t length)
| Calculate the net length of a string.
static size_t | SlCalcStringLen (const void *ptr, size_t length, VarType conv)
| Calculate the gross length of the string that it will occupy in the savegame.
static void | SlString (void *ptr, size_t length, VarType conv)
| Save/Load a string.
static size_t | SlCalcArrayLen (size_t length, VarType conv)
| Return the size in bytes of a certain type of atomic array.
void | SlArray (void *array, size_t length, VarType conv)
| Save/Load an array.
static size_t | ReferenceToInt (const void *obj, SLRefType rt)
| Pointers cannot be saved to a savegame, so this functions gets the index of the item, and if not available, it hussles with pointers (looks really bad :() Remember that a NULL item has value 0, and all indeces have +1, so vehicle 0 is saved as index 1.
static void * | IntToReference (size_t index, SLRefType rt)
| Pointers cannot be loaded from a savegame, so this function gets the index from the savegame and returns the appropiate pointer from the already loaded base.
static size_t | SlCalcListLen (const void *list)
| Return the size in bytes of a list.
static void | SlList (void *list, SLRefType conv)
| Save/Load a list.
static bool | SlIsObjectValidInSavegame (const SaveLoad *sld)
| Are we going to save this object or not?
static bool | SlSkipVariableOnLoad (const SaveLoad *sld)
| Are we going to load this variable when loading a savegame or not?
size_t | SlCalcObjLength (const void *object, const SaveLoad *sld)
| Calculate the size of an object.
size_t | SlCalcObjMemberLength (const void *object, const SaveLoad *sld)
bool | SlObjectMember (void *ptr, const SaveLoad *sld)
void | SlObject (void *object, const SaveLoad *sld)
| Main SaveLoad function.
void | SlGlobList (const SaveLoadGlobVarList *sldg)
| Save or Load (a list of) global variables.
void | SlAutolength (AutolengthProc *proc, void *arg)
| Do something of which I have no idea what it is :P.
static void | SlLoadChunk (const ChunkHandler *ch)
| Load a chunk of data (eg vehicles, stations, etc.
static void | SlStubSaveProc2 (void *arg)
static void | SlStubSaveProc ()
static void | SlSaveChunk (const ChunkHandler *ch)
| Save a chunk of data (eg.
static void | SlSaveChunks ()
| Save all chunks.
static const ChunkHandler * | SlFindChunkHandler (uint32 id)
| Find the ChunkHandler that will be used for processing the found chunk in the savegame or in memory.
static void | SlLoadChunks ()
| Load all chunks.
static void | SlFixPointers ()
| Fix all pointers (convert index -> pointer).
static size_t | ReadNoComp ()
static void | WriteNoComp (size_t size)
static bool | InitNoComp (byte compression)
static void | UninitNoComp ()
static void | WriteMem (size_t size)
static void | UnInitMem ()
static bool | InitMem ()
static const SaveLoadFormat * | GetSavegameFormat (char *s, byte *compression_level)
| Return the savegameformat of the game.
void | InitializeGame (uint size_x, uint size_y, bool reset_date, bool reset_settings)
bool | AfterLoadGame ()
bool | LoadOldSaveGame (const char *file)
static SaveOrLoadResult | AbortSaveLoad ()
| Small helper function to close the to be loaded savegame an signal error.
static void | SaveFileStart ()
| Update the gui accordingly when starting saving and set locks on saveload.
static void | SaveFileDone ()
| Update the gui accordingly when saving is done and release locks on saveload.
void | SetSaveLoadError (StringID str)
| Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friends).
const char * | GetSaveLoadErrorString ()
| Get the string representation of the error message.
static void | SaveFileError ()
| Show a gui message when saving has failed.
static SaveOrLoadResult | SaveFileToDisk (bool threaded)
| We have written the whole game into memory, _memory_savegame, now find and appropiate compressor and start writing to file.
static void | SaveFileToDiskThread (void *arg)
void | WaitTillSaved ()
SaveOrLoadResult | SaveOrLoad (const char *filename, int mode, Subdirectory sb, bool threaded)
| Main Save or Load function where the high-level saveload functions are handled.
void | DoExitSave ()
| Do a save when exiting the game (_settings_client.gui.autosave_on_exit).
void | GenerateDefaultSaveName (char *buf, const char *last)
| Fill the buffer with the default name for a savegame *or* screenshot.
## Variables
const uint16 | SAVEGAME_VERSION = 138
SavegameType | _savegame_type
| type of savegame we are loading
uint32 | _ttdp_version
| version of TTDP savegame (if applicable)
uint16 | _sl_version
| the major savegame version identifier
byte | _sl_minor_version
| the minor savegame version, DO NOT USE!
char | _savegame_format [8]
| how to compress savegames
const ChunkHandler | _gamelog_chunk_handlers []
const ChunkHandler | _map_chunk_handlers []
const ChunkHandler | _misc_chunk_handlers []
const ChunkHandler | _name_chunk_handlers []
const ChunkHandler | _cheat_chunk_handlers []
const ChunkHandler | _setting_chunk_handlers []
const ChunkHandler | _company_chunk_handlers []
const ChunkHandler | _engine_chunk_handlers []
const ChunkHandler | _veh_chunk_handlers []
const ChunkHandler | _waypoint_chunk_handlers []
const ChunkHandler | _depot_chunk_handlers []
const ChunkHandler | _order_chunk_handlers []
const ChunkHandler | _town_chunk_handlers []
const ChunkHandler | _sign_chunk_handlers []
const ChunkHandler | _station_chunk_handlers []
const ChunkHandler | _industry_chunk_handlers []
const ChunkHandler | _economy_chunk_handlers []
const ChunkHandler | _subsidy_chunk_handlers []
const ChunkHandler | _ai_chunk_handlers []
const ChunkHandler | _animated_tile_chunk_handlers []
const ChunkHandler | _newgrf_chunk_handlers []
const ChunkHandler | _group_chunk_handlers []
const ChunkHandler | _cargopacket_chunk_handlers []
const ChunkHandler | _autoreplace_chunk_handlers []
const ChunkHandler | _labelmaps_chunk_handlers []
static const ChunkHandler *const | _chunk_handlers []
static SaveLoadParams | _sl
static AsyncSaveFinishProc | _async_save_finish = NULL
static ThreadObject * | _save_thread
static size_t | _next_offs
static ChunkSaveLoadProc * | _tmp_proc_1
static const uint | NOCOMP_BUFFER_SIZE = 8192
| Buffer size used for the uncompressing 'compressor'.
static const int | MEMORY_CHUNK_SIZE = 128 * 1024
| Save in chunks of 128 KiB.
static AutoFreeSmallVector < byte *, 16 > | _memory_savegame
| Memory allocation for storing savegames in memory.
static ThreadedSave | _ts
static const SaveLoadFormat | _saveload_formats []

## Detailed Description

All actions handling saving and loading goes on in this file.

The general actions are as follows for saving a game (loading is analogous):

1. initialize the writer by creating a temporary memory-buffer for it
2. go through all to-be saved elements, each 'chunk' (ChunkHandler) prefixed by a label
3. use their description array (SaveLoad) to know what elements to save and in what version of the game it was active (used when loading)
4. write all data byte-by-byte to the temporary buffer so it is endian-safe
5. when the buffer is full; flush it to the output (eg save to file) (_sl.buf, _sl.bufp, _sl.bufe)
6. repeat this until everything is done, and flush any remaining output to file

Definition in file saveload.cpp.

## Define Documentation

#define FOR_ALL_CHUNK_HANDLERS | ( | ch |  | ) |

Value:

    for (const ChunkHandler * const *chsc = _chunk_handlers; *chsc != NULL; chsc++) \
        for (const ChunkHandler *ch = *chsc; ch != NULL; ch = (ch->flags & CH_LAST) ? NULL : ch + 1)

Iterate over all chunk handlers.

Parameters:

  | ch | the chunk handler iterator

Definition at line 165 of file saveload.cpp.

Referenced by SlFindChunkHandler(), SlFixPointers(), SlNullPointers(), and SlSaveChunks().

## Enumeration Type Documentation

enum NeedLength

Enumerator:

  NL_NONE | not working in NeedLength mode
  NL_WANTLENGTH | writing length and data
  NL_CALCLENGTH | need to calculate the length

Definition at line 69 of file saveload.cpp.

enum SaveLoadAction

What are we currently doing?

Enumerator:

  SLA_LOAD | loading
  SLA_SAVE | saving
  SLA_PTRS | fixing pointers
  SLA_NULL | null all pointers (on loading error)

Definition at line 62 of file saveload.cpp.

## Function Documentation

void GenerateDefaultSaveName | ( | char * | buf,
|  | const char * | last |
| ) |  |  |

Fill the buffer with the default name for a savegame *or* screenshot.

Parameters:

  | buf | the buffer to write to.
  | last | the last element in the buffer.

Definition at line 2013 of file saveload.cpp.

References _date, _settings_client, GUISettings::date_format_in_default_names, ClientSettings::gui, SanitizeFilename(), and SetDParam().

Referenced by DoAutosave().

static const SaveLoadFormat* GetSavegameFormat | ( | char * | s,
|  | byte * | compression_level |
| ) |  |  | `[static]`

Return the savegameformat of the game.

Whether it was created with ZLIB compression uncompressed, or another type

Parameters:

  | s | Name of the savegame format. If NULL it picks the first available one
  | compression_level | Output for telling what compression level we want.

Returns:
  Pointer to SaveLoadFormat struct giving all characteristics of this type of savegame

Definition at line 1643 of file saveload.cpp.

References Clamp(), SaveLoadFormat::default_compression, endof, SaveLoadFormat::init_write, lastof, SaveLoadFormat::name, ShowInfoF(), and StrEmpty().

Referenced by SaveFileToDisk().

static void * IntToReference | ( | size_t | index,
|  | SLRefType | rt |
| ) |  |  | `[static]`

Pointers cannot be loaded from a savegame, so this function gets the index from the savegame and returns the appropiate pointer from the already loaded base.

Remember that an index of 0 is a NULL pointer so all indeces are +1 so vehicle 0 is saved as 1.

Parameters:

  | index | The index that is being converted to a pointer
  | rt | SLRefType type of the object the pointer is sought of

Returns:
  Return the index converted to a pointer of any type

Definition at line 1545 of file saveload.cpp.

References SaveLoadParams::action, assert_compile(), CheckSavegameVersionOldStyle(), SpecializedStation< Station, false >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::Get(), SpecializedStation< Station, false >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::IsValidID(), SLA_PTRS, and SlError().

Referenced by SlList().

int64 ReadValue | ( | const void * | ptr,
|  | VarType | conv |
| ) |  |  |

Return a signed-long version of the value of a setting.

Parameters:

  | ptr | pointer to the variable
  | conv | type of variable, can be a non-clean type, eg one with other flags because it is parsed

Returns:
  returns the value of the pointer-setting

Definition at line 569 of file saveload.cpp.

References SLE_VAR_NULL.

Referenced by CmdChangeCompanySetting(), CmdChangeSetting(), SettingEntry::DrawSetting(), AIGameSettings::GetValue(), IConsoleGetSetting(), IConsoleListSettings(), ini_save_settings(), LoadSettings(), SetCompanySetting(), SetSettingValue(), and SlSaveLoadConv().

static size_t ReferenceToInt | ( | const void * | obj,
|  | SLRefType | rt |
| ) |  |  | `[static]`

Pointers cannot be saved to a savegame, so this functions gets the index of the item, and if not available, it hussles with pointers (looks really bad :() Remember that a NULL item has value 0, and all indeces have +1, so vehicle 0 is saved as index 1.

Parameters:

  | obj | The object that we want to get the index of
  | rt | SLRefType type of the object the index is being sought of

Returns:
  Return the pointer converted to an index of the type pointed to

Definition at line 1515 of file saveload.cpp.

References SaveLoadParams::action, and SLA_SAVE.

Referenced by SlList().

static void SaveFileStart | ( |  | ) | `[static]`

Update the gui accordingly when starting saving and set locks on saveload.

Also turn off fast-forward cause with that saving takes Aaaaages

Definition at line 1704 of file saveload.cpp.

References InvalidateWindowData(), SBI_SAVELOAD_START, SPR_CURSOR_MOUSE, and CursorVars::sprite.

Referenced by SaveOrLoad().

SaveOrLoadResult SaveOrLoad | ( | const char * | filename,
|  | int | mode,
|  | Subdirectory | sb,
|  | bool | threaded |
| ) |  |  |

Main Save or Load function where the high-level saveload functions are handled.

It opens the savegame, selects format and checks versions

Parameters:

  | filename | The name of the savegame being created/loaded
  | mode | Save or load. Load can also be a TTD(Patch) game. Use SL_LOAD, SL_OLD_LOAD or SL_SAVE
  | sb | The sub directory to save the savegame in
  | threaded | True when threaded saving is allowed

Returns:
  Return the results of the action. SL_OK, SL_ERROR or SL_REINIT ("unload" the game)

Definition at line 1829 of file saveload.cpp.

References _savegame_type, _settings_client, _sl_minor_version, _sl_version, AbortSaveLoad(), SaveLoadParams::action, BASE_DIR, SaveLoadParams::bufe, SaveLoadParams::bufp, endof, SaveLoadParams::excpt_uninit, SaveLoadParams::fh, FioFOpenFile(), GamelogReset(), GamelogStartAction(), GamelogStopAction(), GetSaveLoadErrorString(), GLAT_LOAD, ClientSettings::gui, SaveLoadFormat::init_read, INVALID_STRING_ID, lengthof, SaveLoadFormat::name, ThreadObject::New(), SaveLoadParams::offs_base, SaveLoadParams::read_bytes, SaveLoadFormat::reader, EngineOverrideManager::ResetToDefaultMapping(), SAVE_DIR, SaveFileDone(), SaveFileStart(), SaveFileToDisk(), SAVEGAME_VERSION, SGT_OTTD, ShowErrorMessage(), SL_ERROR, SL_OK, SL_REINIT, SLA_LOAD, SLA_SAVE, SlError(), SlFixPointers(), SlLoadChunks(), SlSaveChunks(), SlWriteFill(), SaveLoadFormat::tag, GUISettings::threaded_saves, SaveLoadFormat::uninit_read, and SaveLoadParams::write_bytes.

Referenced by _GenerateWorld(), DoAutosave(), DoExitSave(), OnNewMonth(), SafeSaveOrLoad(), StartScenario(), and CrashLog::WriteSavegame().

void SlArray | ( | void * | array,
|  | size_t | length,
|  | VarType | conv |
| ) |  |  |

Save/Load an array.

Parameters:

  | array | The array being manipulated
  | length | The length of the array in elements
  | conv | VarType type of the atomic array (int, byte, uint64, etc.)

Definition at line 789 of file saveload.cpp.

References _sl_version, SaveLoadParams::action, BSWAP32(), SaveLoadParams::need_length, NL_CALCLENGTH, NL_NONE, SLA_NULL, SLA_PTRS, SLA_SAVE, SlCalcArrayLen(), SlCalcConvFileLen(), SlCalcConvMemLen(), SlCopyBytes(), SlSaveLoadConv(), and SlSetLength().

Referenced by Load_ANIT(), Load_CAPR(), Load_PRIC(), and Save_ANIT().

void SlAutolength | ( | AutolengthProc * | proc,
|  | void * | arg |
| ) |  |  |

Do something of which I have no idea what it is :P.

Parameters:

  | proc | The callback procedure that is called
  | arg | The variable that will be used for the callback procedure

Definition at line 1081 of file saveload.cpp.

References SaveLoadParams::action, SaveLoadParams::need_length, NL_CALCLENGTH, NL_WANTLENGTH, SaveLoadParams::obj_len, SLA_SAVE, SlError(), and SlSetLength().

static size_t SlCalcArrayLen | ( | size_t | length,
|  | VarType | conv |
| ) |  |  | `[inline, static]`

Return the size in bytes of a certain type of atomic array.

Parameters:

  | length | The length of the array counted in elements
  | conv | VarType type of the variable that is used in calculating the size

Definition at line 778 of file saveload.cpp.

References SlCalcConvFileLen().

Referenced by SlArray().

static byte SlCalcConvFileLen | ( | VarType | conv | ) | `[inline, static]`

Return the size in bytes of a certain type of normal/atomic variable as it appears in a saved game.

See VarTypes

Parameters:

  | conv | VarType type of variable that is used for calculating the size

Returns:
  Return the size of this type in bytes

Definition at line 281 of file saveload.cpp.

References GB(), and lengthof.

Referenced by SlArray(), and SlCalcArrayLen().

static uint SlCalcConvMemLen | ( | VarType | conv | ) | `[inline, static]`

Return the size in bytes of a certain type of normal/atomic variable as it appears in memory.

See VarTypes

Parameters:

  | conv | VarType type of variable that is used for calculating the size

Returns:
  Return the size of this type in bytes

Definition at line 259 of file saveload.cpp.

References GB(), lengthof, SLE_VAR_STR, SLE_VAR_STRB, SLE_VAR_STRBQ, and SLE_VAR_STRQ.

Referenced by SlArray(), and SlSkipVariableOnLoad().

static size_t SlCalcListLen | ( | const void * | list | ) | `[inline, static]`

Return the size in bytes of a list.

Parameters:

  | list | The std::list to find the size of

Definition at line 842 of file saveload.cpp.

References CheckSavegameVersion().

Referenced by SlList().

static size_t SlCalcNetStringLen | ( | const char * | ptr,
|  | size_t | length |
| ) |  |  | `[inline, static]`

Calculate the net length of a string.

This is in almost all cases just strlen(), but if the string is not properly terminated, we'll resort to the maximum length of the buffer.

Parameters:

  | ptr | pointer to the stringbuffer
  | length | maximum length of the string (buffer). If -1 we don't care about a maximum length, but take string length as it is.

Returns:
  return the net length of the string

Definition at line 671 of file saveload.cpp.

References min().

Referenced by SlCalcStringLen(), and SlString().

size_t SlCalcObjLength | ( | const void * | object,
|  | const SaveLoad * | sld |
| ) |  |  |

Calculate the size of an object.

Parameters:

  | object | to be measured
  | sld | The SaveLoad description of the object so we know how to manipulate it

Returns:
  size of given objetc

Definition at line 938 of file saveload.cpp.

References SaveLoad::cmd.

Referenced by SlObject().

static size_t SlCalcStringLen | ( | const void * | ptr,
|  | size_t | length,
|  | VarType | conv |
| ) |  |  | `[inline, static]`

Calculate the gross length of the string that it will occupy in the savegame.

This includes the real length, returned by SlCalcNetStringLen and the length that the index will occupy.

Parameters:

  | ptr | pointer to the stringbuffer
  | length | maximum length of the string (buffer size, etc.)
  | conv | type of data been used

Returns:
  return the gross length of the string

Definition at line 684 of file saveload.cpp.

References SlCalcNetStringLen(), SLE_VAR_STR, SLE_VAR_STRB, SLE_VAR_STRBQ, and SLE_VAR_STRQ.

static void SlCopyBytes | ( | void * | ptr,
|  | size_t | length |
| ) |  |  | `[static]`

Save/Load bytes.

These do not need to be converted to Little/Big Endian so directly write them or read them to/from file

Parameters:

  | ptr | The source or destination of the object being manipulated
  | length | number of bytes this fast CopyBytes lasts

Definition at line 537 of file saveload.cpp.

References SaveLoadParams::action, SLA_LOAD, SLA_SAVE, SlReadByteInternal(), and SlWriteByteInternal().

Referenced by SlArray(), and SlString().

static void NORETURN SlError | ( | StringID | string,
|  | const char * | extra_msg = `NULL` |
| ) |  |  | `[static]`

Error handler, calls longjmp to simulate an exception.

Todo:
  this was used to have a central place to handle errors, but it is pretty ugly, and seriously interferes with any multithreaded approaches

Definition at line 193 of file saveload.cpp.

References SaveLoadParams::error_str, SaveLoadParams::extra_msg, and SlNullPointers().

Referenced by IntToReference(), SaveFileToDisk(), SaveOrLoad(), SlAutolength(), SlIterateArray(), SlLoadChunk(), SlLoadChunks(), SlReadFill(), and SlReadSimpleGamma().

static const ChunkHandler* SlFindChunkHandler | ( | uint32 | id | ) | `[static]`

Find the ChunkHandler that will be used for processing the found chunk in the savegame or in memory.

Parameters:

  | id | the chunk in question

Returns:
  returns the appropiate chunkhandler

Definition at line 1203 of file saveload.cpp.

References FOR_ALL_CHUNK_HANDLERS.

Referenced by SlLoadChunks().

void SlGlobList | ( | const SaveLoadGlobVarList * | sldg | ) |

Save or Load (a list of) global variables.

Parameters:

  | sldg | The global variable that is being loaded or saved

Definition at line 1071 of file saveload.cpp.

References SlObject().

int SlIterateArray | ( |  | ) |

Iterate through the elements of an array and read the whole thing.

Returns:
  The index of the object, or -1 if we have reached the end of current block

Definition at line 459 of file saveload.cpp.

References SaveLoadParams::array_index, SaveLoadParams::block_mode, SaveLoadParams::obj_len, and SlError().

Referenced by Load_SIGN(), and Load_VEHS().

static void SlList | ( | void * | list,
|  | SLRefType | conv |
| ) |  |  | `[static]`

Save/Load a list.

Parameters:

  | list | The list being manipulated
  | conv | SLRefType type of the list (Vehicle *, Station *, etc)

Definition at line 858 of file saveload.cpp.

References SaveLoadParams::action, CheckSavegameVersion(), IntToReference(), SaveLoadParams::need_length, NL_CALCLENGTH, NL_NONE, ReferenceToInt(), SLA_LOAD, SLA_NULL, SLA_PTRS, SLA_SAVE, SlCalcListLen(), and SlSetLength().

static void SlLoadChunk | ( | const ChunkHandler * | ch | ) | `[static]`

Load a chunk of data (eg vehicles, stations, etc.

)

Parameters:

  | ch | The chunkhandler that will be used for the operation

Definition at line 1108 of file saveload.cpp.

References SaveLoadParams::array_index, SaveLoadParams::block_mode, SaveLoadParams::obj_len, SlError(), and SlReadByte().

Referenced by SlLoadChunks().

void SlObject | ( | void * | object,
|  | const SaveLoad * | sld |
| ) |  |  |

Main SaveLoad function.

Parameters:

  | object | The object that is being saved or loaded
  | sld | The SaveLoad description of the object so we know how to manipulate it

Definition at line 1053 of file saveload.cpp.

References SaveLoad::address, SaveLoad::cmd, GetVariableAddress(), SaveLoad::global, SaveLoadParams::need_length, NL_CALCLENGTH, NL_NONE, SlCalcObjLength(), and SlSetLength().

Referenced by Load_ECMY(), Load_SIGN(), Load_VEHS(), Save_ECMY(), Save_SIGN(), Save_VEHS(), and SlGlobList().

static byte SlReadByteInternal | ( |  | ) | `[inline, static]`

Read in a single byte from file.

If the temporary buffer is full, flush it to its final destination

Returns:
  return the read byte from file

Definition at line 315 of file saveload.cpp.

References SaveLoadParams::bufe, SaveLoadParams::bufp, and SlReadFill().

Referenced by SlCopyBytes(), and SlReadByte().

static uint SlReadSimpleGamma | ( |  | ) | `[static]`

Read in the header descriptor of an object or an array.

If the highest bit is set (7), then the index is bigger than 127 elements, so use the next byte to read in the real value. The actual value is then both bytes added with the first shifted 8 bits to the left, and dropping the highest bit (which only indicated a big index). x = ((x & 0x7F) << 8) + SlReadByte();

Returns:
  Return the value of the index

Definition at line 383 of file saveload.cpp.

References HasBit(), SlError(), and SlReadByte().

static void SlSaveChunk | ( | const ChunkHandler * | ch | ) | `[static]`

Save a chunk of data (eg.

vehicles, stations, etc.). Each chunk is prefixed by an ID identifying it, followed by data, and terminator where appropiate

Parameters:

  | ch | The chunkhandler that will be used for the operation

Definition at line 1150 of file saveload.cpp.

References SaveLoadParams::block_mode, SaveLoadParams::last_array_index, SaveLoadParams::need_length, NL_WANTLENGTH, and SlWriteByte().

Referenced by SlSaveChunks().

static void SlSaveLoadConv | ( | void * | ptr,
|  | VarType | conv |
| ) |  |  | `[static]`

Handle all conversion and typechecking of variables here.

In the case of saving, read in the actual value from the struct and then write them to file, endian safely. Loading a value goes exactly the opposite way

Parameters:

  | ptr | The object being filled/read
  | conv | VarType type of the current element of the struct

Definition at line 617 of file saveload.cpp.

References SaveLoadParams::action, ReadValue(), RemapOldStringID(), SLA_LOAD, SLA_NULL, SLA_PTRS, SLA_SAVE, SLE_FILE_STRINGID, SlReadByte(), SlWriteByte(), and WriteValue().

Referenced by SlArray().

void SlSetLength | ( | size_t | length | ) |

Sets the length of either a RIFF object or the number of items in an array.

This lets us load an object or an array of arbitrary size

Parameters:

  | length | The length of the sought object/array

Definition at line 494 of file saveload.cpp.

References SaveLoadParams::action, SaveLoadParams::array_index, SaveLoadParams::block_mode, SaveLoadParams::last_array_index, SaveLoadParams::need_length, NL_CALCLENGTH, NL_NONE, NL_WANTLENGTH, SaveLoadParams::obj_len, and SLA_SAVE.

Referenced by Save_ANIT(), SaveSettings(), SlArray(), SlAutolength(), SlList(), and SlObject().

static void SlSkipBytes | ( | size_t | length | ) | `[inline, static]`

Read in bytes from the file/data structure but don't do anything with them, discarding them in effect.

Parameters:

  | length | The amount of bytes that is being treated this way

Definition at line 556 of file saveload.cpp.

References SlReadByte().

Referenced by SlSkipVariableOnLoad(), and SlString().

static bool SlSkipVariableOnLoad | ( | const SaveLoad * | sld | ) | `[inline, static]`

Are we going to load this variable when loading a savegame or not?

Note:
  If the variable is skipped it is skipped in the savegame bytestream itself as well, so there is no need to skip it somewhere else

Definition at line 922 of file saveload.cpp.

References SaveLoadParams::action, SaveLoad::conv, SaveLoad::length, SLA_SAVE, SlCalcConvMemLen(), SLF_NETWORK_NO, and SlSkipBytes().

static void SlString | ( | void * | ptr,
|  | size_t | length,
|  | VarType | conv |
| ) |  |  | `[static]`

Save/Load a string.

Parameters:

  | ptr | the string being manipulated
  | length | of the string (full length)
  | conv | must be SLE_FILE_STRING

Definition at line 712 of file saveload.cpp.

References SaveLoadParams::action, SLA_LOAD, SLA_NULL, SLA_PTRS, SLA_SAVE, SlCalcNetStringLen(), SlCopyBytes(), SLE_VAR_STR, SLE_VAR_STRB, SLE_VAR_STRBQ, SLE_VAR_STRQ, SlSkipBytes(), and str_validate().

static void SlWriteByteInternal | ( | byte | b | ) | `[inline, static]`

Write away a single byte from memory.

If the temporary buffer is full, flush it to its destination (file)

Parameters:

  | b | the byte that is currently written

Definition at line 328 of file saveload.cpp.

References SaveLoadParams::bufe, SaveLoadParams::bufp, and SlWriteFill().

Referenced by SlCopyBytes(), and SlWriteByte().

static void SlWriteFill | ( |  | ) | `[static]`

Flush the output buffer by writing to disk with the given reader.

If the buffer pointer has not yet been set up, set it up now. Usually only called when the buffer is full, or there is no more data to be processed

Definition at line 296 of file saveload.cpp.

References SaveLoadParams::buf, SaveLoadParams::bufe, SaveLoadParams::bufp, SaveLoadParams::bufsize, SaveLoadParams::offs_base, and SaveLoadParams::write_bytes.

Referenced by SaveOrLoad(), and SlWriteByteInternal().

static void SlWriteSimpleGamma | ( | size_t | i | ) | `[static]`

Write the header descriptor of an object or an array.

If the element is bigger than 127, use 2 bytes for saving and use the highest byte of the first written one as a notice that the length consists of 2 bytes, etc.. like this: 0xxxxxxx 10xxxxxx xxxxxxxx 110xxxxx xxxxxxxx xxxxxxxx 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx

Parameters:

  | i | Index being written

Definition at line 415 of file saveload.cpp.

References SlWriteByte().

void WriteValue | ( | void * | ptr,
|  | VarType | conv,
|  | int64 | val |
| ) |  |  |

Write the value of a setting.

Parameters:

  | ptr | pointer to the variable
  | conv | type of variable, can be a non-clean type, eg with other flags. It is parsed upon read
  | val | the new value being given to the variable

Definition at line 591 of file saveload.cpp.

References CopyFromOldName(), SLE_VAR_NAME, and SLE_VAR_NULL.

Referenced by CmdChangeCompanySetting(), CmdChangeSetting(), SlSaveLoadConv(), and Write_ValidateSetting().

## Variable Documentation

const ChunkHandler* const _chunk_handlers[]`[static]`

Initial value:

     {
      _gamelog_chunk_handlers,
      _map_chunk_handlers,
      _misc_chunk_handlers,
      _name_chunk_handlers,
      _cheat_chunk_handlers,
      _setting_chunk_handlers,
      _veh_chunk_handlers,
      _waypoint_chunk_handlers,
      _depot_chunk_handlers,
      _order_chunk_handlers,
      _industry_chunk_handlers,
      _economy_chunk_handlers,
      _subsidy_chunk_handlers,
      _engine_chunk_handlers,
      _town_chunk_handlers,
      _sign_chunk_handlers,
      _station_chunk_handlers,
      _company_chunk_handlers,
      _ai_chunk_handlers,
      _animated_tile_chunk_handlers,
      _newgrf_chunk_handlers,
      _group_chunk_handlers,
      _cargopacket_chunk_handlers,
      _autoreplace_chunk_handlers,
      _labelmaps_chunk_handlers,
      NULL,
    }

Definition at line 132 of file saveload.cpp.

AutoFreeSmallVector<byte *, 16> _memory_savegame`[static]`

Memory allocation for storing savegames in memory.

Definition at line 1367 of file saveload.cpp.

const SaveLoadFormat _saveload_formats[]`[static]`

Initial value:

     {

      {"lzo",    TO_BE32X('OTTD'), NULL,         NULL,       NULL,           NULL,          NULL,        NULL,            0, 0, 0},

      {"none",   TO_BE32X('OTTN'), InitNoComp,   ReadNoComp, UninitNoComp,   InitNoComp,    WriteNoComp, UninitNoComp,    0, 0, 0},

      {"zlib",   TO_BE32X('OTTZ'), NULL,         NULL,       NULL,           NULL,          NULL,        NULL,            0, 0, 0},

    }

Definition at line 1622 of file saveload.cpp.

const int MEMORY_CHUNK_SIZE = 128 * 1024`[static]`

Save in chunks of 128 KiB.

Definition at line 1365 of file saveload.cpp.