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 "../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 "../fios.h"
#include "../gui.h"
#include "table/strings.h"
#include "saveload_internal.h"
#include "saveload_filter.h"
#include <lzo/lzo1x.h>
#include <zlib.h>

Go to the source code of this file.

Data Structures

struct  ReadBuffer
 A buffer for reading (and buffering) savegame data. More...
struct  MemoryDumper
 Container for dumping the savegame (quickly) to memory. More...
struct  SaveLoadParams
 The saveload struct, containing reader-writer functions, buffer, version, etc. More...
struct  FileReader
 Yes, simply reading from a file. More...
struct  FileWriter
 Yes, simply writing to a file. More...
struct  LZOLoadFilter
 Filter using LZO compression. More...
struct  LZOSaveFilter
 Filter using LZO compression. More...
struct  NoCompLoadFilter
 Filter without any compression. More...
struct  NoCompSaveFilter
 Filter without any compression. More...
struct  ZlibLoadFilter
 Filter using Zlib compression. More...
struct  ZlibSaveFilter
 Filter using Zlib compression. More...
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(* AsyncSaveFinishProc )()
 Callback for when the savegame loading is finished.

Enumerations

enum  SaveLoadAction {
  SLA_LOAD, SLA_SAVE, SLA_PTRS, SLA_NULL,
  SLA_LOAD_CHECK
}
 

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).
void NORETURN SlError (StringID string, const char *extra_msg)
 Error handler.
void NORETURN SlErrorCorrupt (const char *msg)
 Error handler for corrupt savegames.
static void SetAsyncSaveFinish (AsyncSaveFinishProc proc)
 Called by save thread to tell we finished saving.
void ProcessAsyncSaveFinish ()
 Handle async save finishes.
byte SlReadByte ()
 Wrapper for reading a byte from the buffer.
void SlWriteByte (byte b)
 Wrapper for writing a byte to the dumper.
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 void SlSkipBytes (size_t length)
 Read in bytes from the file/data structure but don't do anything with them, discarding them in effect.
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 uint SlReadArrayLength ()
static void SlWriteArrayLength (size_t length)
static uint SlGetArrayLength (size_t length)
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).
void SlSetArrayIndex (uint index)
int SlIterateArray ()
 Iterate through the elements of an array and read the whole thing.
void SlSkipArray ()
 Skip an array or sparse array.
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.
size_t SlGetFieldLength ()
 Get the length of the current object.
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 indices 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 SlLoadCheckChunk (const ChunkHandler *ch)
 Load a chunk of data for checking savegames.
static void SlStubSaveProc2 (void *arg)
 Stub Chunk handlers to only calculate length and do nothing else.
static void SlStubSaveProc ()
 Stub Chunk handlers to only calculate length and do nothing else.
static void SlSaveChunk (const ChunkHandler *ch)
 Save a chunk of data (eg.
static void SlSaveChunks ()
 Save all chunks.
static const ChunkHandlerSlFindChunkHandler (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 SlLoadCheckChunks ()
 Load all chunks for savegame checking.
static void SlFixPointers ()
 Fix all pointers (convert index -> pointer).
static const SaveLoadFormatGetSavegameFormat (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 ()
 Perform a (large) amount of savegame conversion *magic* in order to load older savegames and to fill the caches for various purposes.
bool LoadOldSaveGame (const char *file)
static void ClearSaveLoadState ()
 Clear/free saveload state.
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)
 Thread run function for saving the file to disk.
void WaitTillSaved ()
static SaveOrLoadResult DoSave (SaveFilter *writer, bool threaded)
 Actually perform the saving of the savegame.
SaveOrLoadResult SaveWithFilter (SaveFilter *writer, bool threaded)
 Save the game using a (writer) filter.
static SaveOrLoadResult DoLoad (LoadFilter *reader, bool load_check)
 Actually perform the loading of a "non-old" savegame.
SaveOrLoadResult LoadWithFilter (LoadFilter *reader)
 Load the game using a (reader) filter.
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 = 160
 Current savegame version of OpenTTD.
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
bool _do_autosave
 are we doing an autosave at the moment?
static const size_t MEMORY_CHUNK_SIZE = 128 * 1024
 Save in chunks of 128 KiB.
static SaveLoadParams _sl
 Parameters used for/at saveload.
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 []
const ChunkHandler _airport_chunk_handlers []
const ChunkHandler _object_chunk_handlers []
static const ChunkHandler *const _chunk_handlers []
 Array of all chunks in a savegame, NULL terminated.
static AsyncSaveFinishProc _async_save_finish = NULL
 Callback to call when the savegame loading is finished.
static ThreadObject_save_thread
 The thread we're using to compress and write a savegame.
static size_t _next_offs
static ChunkSaveLoadProc * _stub_save_proc
 Stub Chunk handlers to only calculate length and do nothing else.
static const uint LZO_BUFFER_SIZE = 8192
 Buffer size for the LZO compressor.
static const SaveLoadFormat _saveload_formats []
 The different saveload formats known/understood by OpenTTD.

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 444 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 248 of file saveload.cpp.

What are we currently doing?

Enumerator:
SLA_LOAD 

loading

SLA_SAVE 

saving

SLA_PTRS 

fixing pointers

SLA_NULL 

null all pointers (on loading error)

SLA_LOAD_CHECK 

partial loading into _load_check_data

Definition at line 240 of file saveload.cpp.


Function Documentation

bool AfterLoadGame (  ) 

Perform a (large) amount of savegame conversion *magic* in order to load older savegames and to fill the caches for various purposes.

Returns:
True iff conversion went without a problem.

Definition at line 482 of file afterload.cpp.

References _animated_tile_count, _animated_tile_list, _cur_year, _current_company, _date, _grfconfig, _industry_builder, _m, _me, _network_dedicated, _network_server, _networking, _old_vds, _pause_mode, _road_stop_stop_frame, _settings_client, _settings_game, _tile_type_procs, _tunnel_visibility_frame, Vehicle::acceleration, IndustrySpec::accepts_cargo, Industry::accepts_cargo, AddInflation(), AfterLoadRoadStops(), AfterLoadVehicles(), AIR_AIRCRAFT, AircraftNextAirportPos_and_Order(), Station::airport, EconomySettings::allow_town_roads, AT_OILRIG, CompanyProperties::avail_railtypes, Company::avail_roadtypes, Subsidy::awarded, AXIS_X, AXIS_Y, AxisToDirection(), CompanyProperties::bankrupt_asked, IndustrySpec::behaviour, Depot::build_date, Object::build_date, BaseStation::build_date, Vehicle::build_year, Station::bus_stops, GroundVehicleCache::cached_total_length, CalcClosestTownFromTile(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_cargo_payment_pool >::CanAllocateItem(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_object_pool >::CanAllocateItem(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_roadstop_pool >::CanAllocateItem(), GoodsEntry::cargo, Vehicle::cargo_payment, Subsidy::cargo_type, CeilDiv(), ChangeTileOwner(), Clamp(), CLEAR_FIELDS, ConstructionSettings::clear_frame_burst, CLEAR_GRASS, CompanyProperties::clear_limit, CLEAR_SNOW, ClearBridgeMiddle(), ClosestTownFromTile(), ClrBit(), Object::colour, ClientSettings::company, COMPANY_FIRST, ConnectMultiheadedTrains(), Train::ConsistChanged(), GameSettings::construction, ConvertFromOldCompanyManagerFace(), Order::ConvertFromOldSavegame(), ConvertOldMultiheadToNew(), CopyFromOldName(), CopyTempEngineData(), CargoList< Tinst >::Count(), CT_NO_REFIT, Vehicle::cur_auto_order_index, Vehicle::cur_real_order_index, Vehicle::cur_speed, Vehicle::current_order, CargoPayment::current_station, Vehicle::date_of_last_service, DAY_TICKS, DAYS_TILL_ORIGINAL_BASE_YEAR, DEBUG, DeleteAnimatedTile(), Vehicle::dest_tile, DIAGDIR_END, DIAGDIR_NE, DIAGDIR_NW, DIAGDIR_SE, DIAGDIR_SW, DiagDirToAxis(), DiagDirToDiagTrackBits(), DiagDirToDiagTrackdir(), DiagDirToDir(), GameSettings::difficulty, Vehicle::direction, DirToDiagDir(), VehicleSettings::disable_elrails, Station::dock_tile, DoStartupNewCompany(), Subsidy::dst, Subsidy::dst_type, VehicleSettings::dynamic_engines, GameSettings::economy, EF_ROAD_TRAM, CompanySettings::engine_renew, Company::engine_renew_list, CompanySettings::engine_renew_money, CompanySettings::engine_renew_months, Vehicle::engine_type, CompanyProperties::face, FACIL_DOCK, FACIL_TRAIN, BaseStation::facilities, SpecializedVehicle< T, Type >::First(), Vehicle::FirstShared(), FixOwnerOfRailTrack(), FixVehicleInclination(), FLYING, FOR_ALL_AIRCRAFT, FOR_ALL_DISASTERVEHICLES, FOR_ALL_VEHICLES, Industry::founder, OrderList::FreeChain(), ConstructionSettings::freeform_edges, SpecializedVehicle< RoadVehicle, Type >::From(), SpecializedVehicle< Train, Type >::From(), SpecializedStation< Station, false >::From(), CargoPayment::front, GameSettings::game_creation, GamelogGRFAddList(), GamelogGRFCompatible(), GamelogGRFRemove(), GamelogOldver(), GamelogPrintDebug(), GamelogTestMode(), GamelogTestRevision(), GB(), GroundVehicle< T, Type >::gcache, GCF_COMPATIBLE, GCS_NOT_FOUND, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_company_pool >::Get(), CargoSpec::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_town_pool >::Get(), SpecializedStation< Station, false >::Get(), GetAircraftFlyingAltitude(), SpecializedStation< Waypoint, true >::GetByTile(), SpecializedStation< Station, false >::GetByTile(), BaseStation::GetByTile(), GetClearDensity(), GetCompanyRailtypes(), GetCompanyRoadtypes(), Order::GetDestination(), OrderList::GetFirstOrder(), GetHouseType(), SpecializedStation< Station, false >::GetIfValid(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_vehicle_pool >::GetIfValid(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_company_pool >::GetIfValid(), GetIndustryGfx(), GetIndustrySpec(), GetIndustryType(), GetNorthernBridgeEnd(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_town_pool >::GetNumItems(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_object_pool >::GetNumItems(), Vehicle::GetNumOrders(), GetObjectType(), GetOtherShipDepotTile(), GetOtherTunnelBridgeEnd(), GetRailType(), GetRawClearGround(), GetRoadOwner(), GetRoadTileType(), Airport::GetSpec(), GetStationGfx(), GetStationType(), GetTargetAirportIfValid(), GetTileOwner(), GetTileSlope(), GetTileTrackStatus(), GetTileType(), GetTunnelBridgeDirection(), GetTunnelBridgeTransportType(), Order::GetUnloadType(), GetWaterClass(), GetWaterTileType(), GLC_ALL_GOOD, GLC_COMPATIBLE, GLC_NOT_FOUND, Station::goods, GroundVehicle< T, Type >::gv_flags, TileArea::h, HasBit(), HasSignals(), HasStationRail(), HasTownOwnedRoad(), CompanyProperties::inaugurated_year, Object::IncTypeCount(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, Station::indtype, DifficultySettings::industry_density, INDUSTRYBEH_BUILT_ONWATER, INDUSTRYBEH_PLANT_ON_BUILT, Economy::inflation_prices, InitializeRailGUI(), InitializeWindowsAndCaches(), INVALID_COMPANY, INVALID_DIR, INVALID_OWNER, INVALID_STRING_ID, INVALID_TILE, INVALID_TRACK, CompanyProperties::is_ai, IsAirportTile(), IsBridge(), IsBridgeTile(), IsBuoy(), IsBuoyTile(), IsClearGround(), IsDock(), IsDriveThroughStopTile(), SpecializedStation< Station, false >::IsExpected(), GroundVehicle< T, Type >::IsFreeWagon(), Vehicle::IsFrontEngine(), IsGoodGRFConfigList(), Vehicle::IsGroundVehicle(), IsHouseCompleted(), IsInsideMM(), IsLevelCrossing(), IsLevelCrossingTile(), IsLock(), Aircraft::IsNormalAircraft(), IsOilRig(), IsPlainRail(), IsPlainRailTile(), Vehicle::IsPrimaryVehicle(), IsRailDepot(), IsRailDepotTile(), IsRoadDepot(), IsRoadStop(), IsSavegameVersionBefore(), IsShipDepot(), IsStatueTile(), IsTileOwner(), IsTileType(), IsTruckStop(), IsTunnelTile(), Order::IsType(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_industry_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_town_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_company_pool >::IsValidID(), IsWater(), EconomySettings::larger_towns, Industry::last_prod_year, Vehicle::last_station_visited, Town::layout, lengthof, Vehicle::list, Vehicle::load_unload_ticks, LoadStringWidthTable(), Object::location, CompanyProperties::location_of_HQ, Tile::m1, Tile::m2, Tile::m3, Tile::m4, Tile::m5, TileExtended::m7, MakeCanal(), MakeClear(), MakeDefaultName(), MakeRoadNormal(), MakeSea(), MakeShore(), MapMaxX(), MapMaxY(), MapSize(), MAX_COMPANIES, MAX_INFLATION, DifficultySettings::max_loan, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::MAX_SIZE, VehicleSettings::max_train_length, MayHaveBridgeAbove(), min(), MoveBuoysToWaypoints(), MoveWaypointsToBaseStations(), MP_CLEAR, MP_HOUSE, MP_INDUSTRY, MP_OBJECT, MP_RAILWAY, MP_ROAD, MP_STATION, MP_TREES, MP_TUNNELBRIDGE, MP_VOID, MP_WATER, BaseStation::name, CompanyProperties::name, CompanyProperties::name_1, PathfinderSettings::new_pathfinding_all, GRFConfig::next, NUM_CARGO, DifficultySettings::number_towns, OBJECT_HQ, OBJECT_STATUE, Economy::old_max_loan_unround, Economy::old_max_loan_unround_fract, OLFB_NO_LOAD, ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS, Vehicle::orders, ORIGINAL_BASE_YEAR, OSL_PLATFORM_FAR_END, OUFB_TRANSFER, OUFB_UNLOAD, BaseStation::owner, OWNER_NONE, OWNER_TOWN, OWNER_WATER, PathfinderSettings::pathfinder_for_roadvehs, PathfinderSettings::pathfinder_for_ships, PathfinderSettings::pathfinder_for_trains, GameSettings::pf, PM_PAUSED_ERROR, PM_PAUSED_NORMAL, PM_UNPAUSED, CompanyProperties::president_name, CompanyProperties::president_name_1, Industry::produced_cargo, Vehicle::profit_last_year, Vehicle::profit_this_year, YAPFSettings::rail_use_yapf, RAILTYPE_ELECTRIC, RAILTYPE_RAIL, RATING_INITIAL, Town::ratings, BaseStation::rect, Subsidy::remaining, CompanySettings::renew_keep_length, Train::ReserveTrackUnderConsist(), IndustryBuildData::Reset(), ResetCompanyLivery(), ResetOldNames(), ResetSignalHandlers(), Backup< T >::Restore(), PathfinderSettings::reverse_at_signals, ReverseDiagDir(), ReverseDir(), VehicleSettings::road_side, ROAD_TILE_CROSSING, ROAD_TILE_DEPOT, ROAD_TILE_NORMAL, YAPFSettings::road_use_yapf, ROAD_X, ROAD_Y, ROADTYPE_END, ROADTYPE_ROAD, ROADTYPES_ROAD, Vehicle::running_ticks, RVS_DRIVE_SIDE, RVS_ENTERED_STOP, RVS_IN_DT_ROAD_STOP, RVS_IN_ROAD_STOP, RVSB_IN_DEPOT, RVSB_IN_ROAD_STOP, RVSB_WORMHOLE, SB(), SetAircraftPosition(), SetAnimationFrame(), SetBit(), SetBridgeMiddle(), SetClearGroundDensity(), SetCrossingReservation(), SetDate(), SetDepotReservation(), SetFenceSE(), SetFenceSW(), SetHouseCompleted(), SetLiftPosition(), Order::SetLoadType(), Order::SetNonStopType(), SetRailStationReservation(), SetRailType(), Order::SetRefit(), SetRoadOwner(), SetRoadTypes(), SetSaveLoadError(), SetSignalHandlers(), SetSignalStates(), SetStationGfx(), Order::SetStopLocation(), SetTileOwner(), Company::settings, SettingsDisableElrail(), SetTownIndex(), SetTrackReservation(), SetTropicZone(), SetTunnelBridgeReservation(), Order::SetUnloadType(), SetWaterClass(), SetWaterClassDependingOnSurroundings(), CompanyProperties::share_owners, YAPFSettings::ship_use_yapf, SIG_ELECTRIC, SIG_SEMAPHORE, SIGTYPE_COMBO, AirportSpec::size_x, AirportSpec::size_y, SlError(), SlErrorCorrupt(), SLOPE_FLAT, Subsidy::src, Subsidy::src_type, ST_INDUSTRY, ST_TOWN, AI::StartNew(), Aircraft::state, RoadVehicle::state, BaseStation::string_id, Vehicle::subtype, Swap(), TE_FOOD, TE_GOODS, TE_MAIL, TE_PASSENGERS, ConstructionSettings::terraform_frame_burst, CompanyProperties::terraform_limit, TFP_NONE, TFP_STUCK, Vehicle::tile, TileArea::tile, TILE_ADDXY, TILE_SIZE, TILE_UNIT_MASK, TileHash(), TileHeight(), TileX(), TileXY(), TileY(), TL_BETTER_ROADS, TL_RANDOM, BaseStation::town, Object::town, Waypoint::town_cn, Depot::town_cn, CargoSpec::town_effect, TOWN_HOUSE_COMPLETED, EconomySettings::town_layout, GameCreationSettings::town_name, TRACK_BIT_NONE, TRACK_BIT_WORMHOLE, TRACK_BIT_X, TRACK_BIT_Y, TRACK_LOWER, TRACK_UPPER, TRACK_X, TrackStatusToTrackBits(), BaseStation::train_station, TRANSPORT_RAIL, TRANSPORT_ROAD, TREE_GROUND_SNOW_DESERT, TROPICZONE_NORMAL, Station::truck_stops, Aircraft::turn_counter, Industry::type, BaseVehicle::type, Airport::type, UpdateAircraftCache(), UpdateHousesAndTowns(), UpdateLevelCrossing(), UpdateNearestTownForRoadTiles(), UpdateOldAircraft(), Vehicle::UpdateRealOrderIndex(), UpdateStationAcceptance(), VEH_INVALID, VEH_ROAD, VEH_SHIP, VEH_TRAIN, CompanySettings::vehicle, GameSettings::vehicle, Vehicle::vehicle_flags, Vehicle::vehstatus, VF_LOADING_FINISHED, VF_PATHFINDER_LOST, VPF_NPF, VPF_OPF, VPF_YAPF, VS_CRASHED, VS_HIDDEN, VS_STOPPED, TileArea::w, Train::wait_counter, PathfinderSettings::wait_for_pbs_path, PathfinderSettings::wait_oneway_signal, PathfinderSettings::wait_twoway_signal, WATER_CLASS_CANAL, WATER_CLASS_INVALID, WATER_CLASS_RIVER, WATER_CLASS_SEA, Vehicle::x_pos, BaseStation::xy, XYNSToDiagDir(), Vehicle::y_pos, PathfinderSettings::yapf, YapfNotifyTrackLayoutChange(), and Vehicle::z_pos.

Referenced by DoLoad(), and SaveOrLoad().

static SaveOrLoadResult DoLoad ( LoadFilter reader,
bool  load_check 
) [static]
static SaveOrLoadResult DoSave ( SaveFilter writer,
bool  threaded 
) [static]

Actually perform the saving of the savegame.

General tactic is to first save the game to memory, then write it to file using the writer, either in threaded mode if possible, or single-threaded.

Parameters:
writer The filter to write the savegame to.
threaded Whether to try to perform the saving asynchroniously.
Returns:
Return the result of the action. SL_OK or SL_ERROR

Definition at line 2432 of file saveload.cpp.

References _sl_version, DEBUG, SaveLoadParams::dumper, ThreadObject::New(), SaveFileDone(), SaveFileStart(), SaveFileToDisk(), SaveFileToDiskThread(), SAVEGAME_VERSION, SaveLoadParams::saveinprogress, SaveLoadParams::sf, SL_OK, and SlSaveChunks().

Referenced by SaveOrLoad(), and SaveWithFilter().

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 2725 of file saveload.cpp.

References _date, _local_company, _settings_client, GUISettings::date_format_in_default_names, ClientSettings::gui, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_company_pool >::IsValidID(), 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 2248 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 indices 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 1192 of file saveload.cpp.

References SaveLoadParams::action, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_cargopacket_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_enginerenew_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_roadstop_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_town_pool >::Get(), SpecializedStation< Station, false >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_vehicle_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_order_pool >::Get(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_orderlist_pool >::Get(), IsSavegameVersionBefore(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_cargopacket_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_enginerenew_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_roadstop_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_town_pool >::IsValidID(), SpecializedStation< Station, false >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_vehicle_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_order_pool >::IsValidID(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_orderlist_pool >::IsValidID(), REF_CARGO_PACKET, REF_ENGINE_RENEWS, REF_ORDER, REF_ORDERLIST, REF_ROADSTOPS, REF_STATION, REF_TOWN, REF_VEHICLE, REF_VEHICLE_OLD, SLA_PTRS, and SlErrorCorrupt().

Referenced by SlList().

SaveOrLoadResult LoadWithFilter ( LoadFilter reader  ) 

Load the game using a (reader) filter.

Parameters:
reader The filter to read the savegame from.
Returns:
Return the result of the action. SL_OK or SL_REINIT ("unload" the game)

Definition at line 2621 of file saveload.cpp.

References SaveLoadParams::action, ClearSaveLoadState(), DoLoad(), SL_REINIT, and SLA_LOAD.

Referenced by SafeLoad().

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 878 of file saveload.cpp.

References GetVarMemType(), and SLE_VAR_NULL.

Referenced by CmdChangeCompanySetting(), CmdChangeSetting(), SettingEntry::DrawSetting(), CheatWindow::DrawWidget(), AIGameSettings::GetValue(), IConsoleGetSetting(), IConsoleListSettings(), IniSaveSettings(), LoadSettings(), GameSettingsWindow::OnClick(), GameDifficultyWindow::OnClick(), CheatWindow::OnClick(), GameDifficultyWindow::OnInvalidateData(), CheatWindow::OnQueryTextFinished(), SetCompanySetting(), SetSettingValue(), GameDifficultyWindow::SetStringParameters(), SlSaveLoadConv(), and SyncCompanySettings().

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 indices 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 1162 of file saveload.cpp.

References SaveLoadParams::action, REF_CARGO_PACKET, REF_ENGINE_RENEWS, REF_ORDER, REF_ORDERLIST, REF_ROADSTOPS, REF_STATION, REF_TOWN, REF_VEHICLE, REF_VEHICLE_OLD, and SLA_SAVE.

Referenced by SlList().

static void SaveFileDone (  )  [static]

Update the gui accordingly when saving is done and release locks on saveload.

Definition at line 2331 of file saveload.cpp.

References SaveLoadParams::ff_state, InvalidateWindowData(), SaveLoadParams::saveinprogress, SBI_SAVELOAD_FINISH, SetMouseCursor(), SPR_CURSOR_MOUSE, and CursorVars::sprite.

Referenced by DoSave(), SaveFileError(), and SaveFileToDisk().

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 2320 of file saveload.cpp.

References SaveLoadParams::ff_state, InvalidateWindowData(), SaveLoadParams::saveinprogress, SBI_SAVELOAD_START, SetMouseCursor(), SPR_CURSOR_MOUSE, and CursorVars::sprite.

Referenced by DoSave().

static void SaveFileToDiskThread ( void *  arg  )  [static]

Thread run function for saving the file to disk.

Definition at line 2410 of file saveload.cpp.

References SaveFileToDisk().

Referenced by DoSave().

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 mode. Load can also be a TTD(Patch) game. Use SL_LOAD, SL_OLD_LOAD, SL_LOAD_CHECK, or SL_SAVE.
sb The sub directory to save the savegame in
threaded True when threaded saving is allowed
Returns:
Return the result of the action. SL_OK, SL_ERROR, or SL_REINIT ("unload" the game)

Definition at line 2641 of file saveload.cpp.

References _date, _do_autosave, _grfconfig, _network_server, _settings_client, _sl_minor_version, _sl_version, SaveLoadParams::action, AfterLoadGame(), BASE_DIR, ClearGRFConfigList(), ClearSaveLoadState(), DEBUG, DoLoad(), DoSave(), FioFOpenFile(), GamelogReset(), GamelogStartAction(), GamelogStopAction(), GetSaveLoadErrorString(), GLAT_LOAD, ClientSettings::gui, INVALID_STRING_ID, EngineOverrideManager::ResetToDefaultMapping(), SAVE_DIR, SaveLoadParams::saveinprogress, ShowErrorMessage(), SL_ERROR, SL_LOAD, SL_LOAD_CHECK, SL_OK, SL_OLD_LOAD, SL_REINIT, SL_SAVE, SLA_LOAD, SLA_LOAD_CHECK, SLA_SAVE, SlError(), GUISettings::threaded_saves, and WL_ERROR.

Referenced by _GenerateWorld(), DEF_CONSOLE_CMD(), DoAutosave(), DoExitSave(), SaveLoadWindow::OnClick(), SafeLoad(), StateGameLoop(), and CrashLog::WriteSavegame().

SaveOrLoadResult SaveWithFilter ( SaveFilter writer,
bool  threaded 
)

Save the game using a (writer) filter.

Parameters:
writer The filter to write the savegame to.
threaded Whether to try to perform the saving asynchroniously.
Returns:
Return the result of the action. SL_OK or SL_ERROR

Definition at line 2463 of file saveload.cpp.

References SaveLoadParams::action, ClearSaveLoadState(), DoSave(), SL_ERROR, and SLA_SAVE.

static void SetAsyncSaveFinish ( AsyncSaveFinishProc  proc  )  [static]

Called by save thread to tell we finished saving.

Parameters:
proc The callback to call when saving is done.

Definition at line 521 of file saveload.cpp.

Referenced by SaveFileToDisk().

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 1107 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(), AIInstance::LoadObjects(), Save_ANIT(), and AIInstance::SaveObject().

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 1499 of file saveload.cpp.

References SaveLoadParams::action, SaveLoadParams::dumper, MemoryDumper::GetSize(), SaveLoadParams::need_length, NL_CALCLENGTH, NL_WANTLENGTH, SaveLoadParams::obj_len, SLA_SAVE, SlErrorCorrupt(), and SlSetLength().

Referenced by SlStubSaveProc().

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 1096 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 734 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 710 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 1255 of file saveload.cpp.

References IsSavegameVersionBefore().

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 985 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 1354 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 1000 of file saveload.cpp.

References GetVarMemType(), 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 849 of file saveload.cpp.

References SaveLoadParams::action, SLA_LOAD, SLA_LOAD_CHECK, SLA_SAVE, SlReadByte(), and SlWriteByte().

Referenced by SlArray(), and SlString().

void NORETURN SlError ( StringID  string,
const char *  extra_msg 
)

Error handler.

Sets everything up to show an error message and to clean up the mess of a partial savegame load.

Parameters:
string The translatable error message to show.
extra_msg An extra error message coming from one of the APIs.
Note:
This function does never return as it throws an exception to break out of all the saveload code.

Definition at line 480 of file saveload.cpp.

References _load_check_data, SaveLoadParams::action, LoadCheckData::error, LoadCheckData::error_data, SaveLoadParams::error_str, SaveLoadParams::extra_msg, SLA_LOAD, SLA_LOAD_CHECK, SLA_PTRS, and SlNullPointers().

Referenced by AfterLoadGame(), DoLoad(), PacketWriter::Finish(), LZOLoadFilter::LZOLoadFilter(), LZOSaveFilter::LZOSaveFilter(), MoveWaypointsToBaseStations(), ZlibLoadFilter::Read(), LZOLoadFilter::Read(), SaveOrLoad(), SlErrorCorrupt(), FileWriter::Write(), PacketWriter::Write(), ZlibSaveFilter::WriteLoop(), ZlibLoadFilter::ZlibLoadFilter(), and ZlibSaveFilter::ZlibSaveFilter().

void NORETURN SlErrorCorrupt ( const char *  msg  ) 

Error handler for corrupt savegames.

Sets everything up to show the error message and to clean up the mess of a partial savegame load.

Parameters:
msg Location the corruption has been spotted.
Note:
This function does never return as it throws an exception to break out of all the saveload code.

Definition at line 507 of file saveload.cpp.

References SlError().

Referenced by AfterLoadGame(), AfterLoadVehicles(), ConvertOldMultiheadToNew(), IntToReference(), Load_VEHS(), LoadOldVehicle(), LZOLoadFilter::Read(), SetWaterClassDependingOnSurroundings(), SlAutolength(), SlIterateArray(), SlLoadCheckChunk(), SlLoadCheckChunks(), SlLoadChunk(), SlLoadChunks(), 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 1694 of file saveload.cpp.

References FOR_ALL_CHUNK_HANDLERS.

Referenced by SlLoadCheckChunks(), and 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 1489 of file saveload.cpp.

References SlObject().

Referenced by LoadSave_IBLD().

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 760 of file saveload.cpp.

References SaveLoadParams::block_mode, DEBUG, ReadBuffer::GetSize(), SaveLoadParams::obj_len, SaveLoadParams::reader, and SlErrorCorrupt().

Referenced by Load_ITBL(), Load_NewGRFMapping(), Load_SIGN(), Load_VEHS(), and SlSkipArray().

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 1271 of file saveload.cpp.

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

static void SlLoadCheckChunk ( const ChunkHandler ch  )  [static]

Load a chunk of data for checking savegames.

If the chunkhandler is NULL, the chunk is skipped.

Parameters:
ch The chunkhandler that will be used for the operation

Definition at line 1564 of file saveload.cpp.

References SaveLoadParams::block_mode, ReadBuffer::GetSize(), ChunkHandler::load_check_proc, SaveLoadParams::obj_len, SaveLoadParams::reader, SlErrorCorrupt(), SlReadByte(), SlSkipArray(), and SlSkipBytes().

Referenced by SlLoadCheckChunks().

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 1526 of file saveload.cpp.

References SaveLoadParams::block_mode, ReadBuffer::GetSize(), ChunkHandler::load_proc, SaveLoadParams::obj_len, SaveLoadParams::reader, SlErrorCorrupt(), and SlReadByte().

Referenced by SlLoadChunks().

void SlObject ( void *  object,
const SaveLoad sld 
)
byte SlReadByte (  ) 

Wrapper for reading a byte from the buffer.

Returns:
The read byte.

Definition at line 551 of file saveload.cpp.

References SaveLoadParams::reader.

Referenced by Load_VEHS(), SlCopyBytes(), SlLoadCheckChunk(), SlLoadChunk(), SlReadSimpleGamma(), SlSaveLoadConv(), and SlSkipBytes().

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 621 of file saveload.cpp.

References HasBit(), SlErrorCorrupt(), 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 1640 of file saveload.cpp.

References SaveLoadParams::block_mode, DEBUG, ChunkHandler::flags, ChunkHandler::id, SaveLoadParams::last_array_index, SaveLoadParams::need_length, NL_WANTLENGTH, ChunkHandler::save_proc, SlStubSaveProc(), 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 928 of file saveload.cpp.

References SaveLoadParams::action, GetVarFileType(), ReadValue(), RemapOldStringID(), SLA_LOAD, SLA_LOAD_CHECK, 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 805 of file saveload.cpp.

References SaveLoadParams::action, 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 607 of file saveload.cpp.

References SlReadByte().

Referenced by SlLoadCheckChunk(), SlSkipArray(), 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 1338 of file saveload.cpp.

References _network_server, _networking, 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 1029 of file saveload.cpp.

References SaveLoadParams::action, DEBUG, GetVarMemType(), SLA_LOAD, SLA_LOAD_CHECK, 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 SlStubSaveProc (  )  [static]

Stub Chunk handlers to only calculate length and do nothing else.

Call SlAutoLenth with our stub save proc that will eventually call the intended chunk handler.

Definition at line 1630 of file saveload.cpp.

References SlAutolength(), and SlStubSaveProc2().

Referenced by SlSaveChunk().

static void SlStubSaveProc2 ( void *  arg  )  [inline, static]

Stub Chunk handlers to only calculate length and do nothing else.

Actually call the intended chunk handler.

Parameters:
arg ignored parameter.

Definition at line 1620 of file saveload.cpp.

References _stub_save_proc.

Referenced by SlStubSaveProc().

void SlWriteByte ( byte  b  ) 

Wrapper for writing a byte to the dumper.

Parameters:
b The byte to write.

Definition at line 560 of file saveload.cpp.

References SaveLoadParams::dumper, and MemoryDumper::WriteByte().

Referenced by SlCopyBytes(), SlSaveChunk(), SlSaveLoadConv(), and SlWriteSimpleGamma().

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 654 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 902 of file saveload.cpp.

References CopyFromOldName(), GetVarMemType(), SLE_VAR_NAME, and SLE_VAR_NULL.

Referenced by CmdChangeCompanySetting(), CmdChangeSetting(), GameDifficultyWindow::OnClick(), CheatWindow::OnClick(), CheatWindow::OnQueryTextFinished(), 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,
  _airport_chunk_handlers,
  _object_chunk_handlers,
  NULL,
}

Array of all chunks in a savegame, NULL terminated.

Definition at line 409 of file saveload.cpp.

Initial value:
 {

  
  {"lzo",    TO_BE32X('OTTD'), CreateLoadFilter<LZOLoadFilter>,    CreateSaveFilter<LZOSaveFilter>,    0, 0, 0},



  
  {"none",   TO_BE32X('OTTN'), CreateLoadFilter<NoCompLoadFilter>, CreateSaveFilter<NoCompSaveFilter>, 0, 0, 0},

  
  {"zlib",   TO_BE32X('OTTZ'), CreateLoadFilter<ZlibLoadFilter>,   CreateSaveFilter<ZlibSaveFilter>,   0, 6, 9},











  {"lzma",   TO_BE32X('OTTX'), NULL,                               NULL,                               0, 0, 0},

}

The different saveload formats known/understood by OpenTTD.

Definition at line 2212 of file saveload.cpp.

ChunkSaveLoadProc* _stub_save_proc [static]

Stub Chunk handlers to only calculate length and do nothing else.

The intended chunk handler that should be called.

Definition at line 1613 of file saveload.cpp.

Referenced by SlStubSaveProc2().

const size_t MEMORY_CHUNK_SIZE = 128 * 1024 [static]

Save in chunks of 128 KiB.

Definition at line 255 of file saveload.cpp.

Referenced by MemoryDumper::Flush(), MemoryDumper::GetSize(), MemoryDumper::WriteByte(), and ZlibSaveFilter::WriteLoop().


Generated on Fri Mar 18 23:17:50 2011 for OpenTTD by  doxygen 1.6.1