OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

Data Structures | Functions | Variables
openttd.cpp File Reference

Functions related to starting OpenTTD. More...

`#include "stdafx.h"`
`#include "blitter/factory.hpp"`
`#include "sound/sound_driver.hpp"`
`#include "music/music_driver.hpp"`
`#include "video/video_driver.hpp"`
`#include "fontcache.h"`
`#include "error.h"`
`#include "gui.h"`
`#include "base_media_base.h"`
`#include "saveload/saveload.h"`
`#include "company_func.h"`
`#include "command_func.h"`
`#include "news_func.h"`
`#include "fios.h"`
`#include "aircraft.h"`
`#include "roadveh.h"`
`#include "train.h"`
`#include "ship.h"`
`#include "console_func.h"`
`#include "screenshot.h"`
`#include "network/network.h"`
`#include "network/network_func.h"`
`#include "ai/ai.hpp"`
`#include "ai/ai_config.hpp"`
`#include "settings_func.h"`
`#include "genworld.h"`
`#include "progress.h"`
`#include "strings_func.h"`
`#include "date_func.h"`
`#include "vehicle_func.h"`
`#include "gamelog.h"`
`#include "animated_tile_func.h"`
`#include "roadstop_base.h"`
`#include "elrail_func.h"`
`#include "rev.h"`
`#include "highscore.h"`
`#include "station_base.h"`
`#include "crashlog.h"`
`#include "engine_func.h"`
`#include "core/random_func.hpp"`
`#include "rail_gui.h"`
`#include "core/backup_type.hpp"`
`#include "hotkeys.h"`
`#include "newgrf.h"`
`#include "misc/getoptdata.h"`
`#include "game/game.hpp"`
`#include "game/game_config.hpp"`
`#include "town.h"`
`#include "subsidy_func.h"`
`#include "gfx_layout.h"`
`#include "viewport_sprite_sorter.h"`
`#include "linkgraph/linkgraphschedule.h"`
`#include <stdarg.h>`
`#include "safeguards.h"`

Go to the source code of this file.

## Data Structures
struct | AfterNewGRFScan
| Callback structure of statements to be executed after the NewGRF scan. More...

## Functions
void | CallLandscapeTick ()
void | IncreaseDate ()
| Increases the tick counter, increases date and possibly calls procedures that have to be called daily, monthly or yearly.
void | DoPaletteAnimations ()
void | MusicLoop ()
void | ResetMusic ()
void | CallWindowTickEvent ()
| Dispatch WE_TICK event over all windows.
bool | HandleBootstrap ()
| Handle all procedures for bootstrapping OpenTTD without a base graphics set.
Company * | DoStartupNewCompany (bool is_ai, CompanyID company=INVALID_COMPANY)
| Create a new company and sets all company variables default values.
void | ShowOSErrorBox (const char *buf, bool system)
void CDECL | usererror (const char *s,...)
| Error handling for fatal user errors.
void CDECL | error (const char *s,...)
| Error handling for fatal non-user errors.
void CDECL | ShowInfoF (const char *str,...)
| Shows some information on the console/a popup box depending on the OS.
static void | ShowHelp ()
| Show the help message when someone passed a wrong parameter.
static void | WriteSavegameInfo (const char *name)
static void | ParseResolution (Dimension *res, const char *s)
| Extract the resolution from the given string and store it in the 'res' parameter.
static void | ShutdownGame ()
| Unitializes drivers, frees allocated memory, cleans pools, ...
static void | LoadIntroGame (bool load_newgrfs=true)
| Load the introduction game.
void | MakeNewgameSettingsLive ()
void | OpenBrowser (const char *url)
int | openttd_main (int argc, char *argv[])
| Main entry point for this lovely game.
void | HandleExitGameRequest ()
static void | MakeNewGameDone ()
static void | MakeNewGame (bool from_heightmap, bool reset_settings)
static void | MakeNewEditorWorldDone ()
static void | MakeNewEditorWorld ()
bool | SafeLoad (const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=NULL)
| Load the specified savegame but on error do different things.
void | SwitchToMode (SwitchMode new_mode)
static void | CheckCaches ()
| Check the validity of some of the caches.
void | StateGameLoop ()
| State controlling game loop.
static void | DoAutosave ()
| Create an autosave.
void | GameLoop ()

## Variables
char * | _config_file
| Configuration file of OpenTTD.
static const OptionData | _options []
| Options of OpenTTD.

## Detailed Description

Functions related to starting OpenTTD.

Definition in file openttd.cpp.

## Function Documentation

static void CheckCaches | ( |  | ) |
| static

Check the validity of some of the caches.

Especially in the sense of desyncs between the cached value and what the value would be when calculated from the 'base' data.

Definition at line 1190 of file openttd.cpp.

References AfterLoadCompanyStats(), SmallVector< T, S >::Append(), Town::cache, Vehicle::cargo, GoodsEntry::cargo, CCF_TRACK, RoadStop::Entry::CheckIntegrity(), Train::ConsistChanged(), DEBUG, DIAGDIR_NE, DIAGDIR_NW, FillNewGRFVehicleCache(), Vehicle::First(), FOR_ALL_VEHICLES, free(), SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), SpecializedVehicle< Ship, VEH_SHIP >::From(), SpecializedVehicle< Train, Type >::From(), SpecializedVehicle< RoadVehicle, Type >::From(), GroundVehicle< T, Type >::gcache, SmallVector< T, S >::Get(), RoadStop::GetEntry(), Station::goods, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, Company::infrastructure, CargoList< Tinst, Tcont >::InvalidateCache(), VehicleCargoList::InvalidateCache(), Vehicle::IsPrimaryVehicle(), IsStandardRoadStopTile(), MemCmpT(), MemCpyT(), Vehicle::Next(), NUM_CARGO, Vehicle::owner, RebuildSubsidisedSourceAndDestinationCache(), RebuildTownCaches(), RoadVehUpdateCache(), BaseVehicle::type, Vehicle::unitnumber, UpdateAircraftCache(), Ship::UpdateCache(), VEH_AIRCRAFT, VEH_ROAD, VEH_SHIP, VEH_TRAIN, Vehicle::vehstatus, VS_CRASHED, and RoadStop::xy.

Referenced by StateGameLoop().

static void DoAutosave | ( |  | ) |
| static

Create an autosave.

The default name is "autosave#.sav". However with the setting 'keep_all_autosave' the name defaults to company-name + date

Definition at line 1405 of file openttd.cpp.

References _networking, _settings_client, AUTOSAVE_DIR, DEBUG, GenerateDefaultSaveName(), ClientSettings::gui, INVALID_STRING_ID, GUISettings::keep_all_autosave, lastof, GUISettings::max_num_autosaves, SaveOrLoad(), seprintf(), ShowErrorMessage(), SL_OK, SL_SAVE, strecat(), and WL_ERROR.

Company* DoStartupNewCompany | ( | bool | is_ai,
|  | CompanyID | company = `INVALID_COMPANY`
| ) |  |

Create a new company and sets all company variables default values.

Parameters

  is_ai | is an AI company?
  company | CompanyID to use for the new company

Returns
  the company struct

Definition at line 533 of file company_cmd.cpp.

void CDECL error | ( | const char * | s,
|  |  | ...
| ) |  |

Error handling for fatal non-user errors.

Parameters

  s | the string to print.

Note
  Does NEVER return.

Definition at line 110 of file openttd.cpp.

References lastof, CrashLog::SetErrorMessage(), and vseprintf().

Referenced by ScriptInfo::AddLabels(), ScriptInfo::AddSetting(), AllocateMap(), ScriptInfo::CheckMethod(), CheckTrainAttachment(), CmdConvertRail(), CmdStartStopVehicle(), CompareFiles(), DEFINE_POOL_METHOD(), DisableStaticNewGRFInfluencingNonStaticNewGRFs(), DoCommand(), FileStringReader::FileStringReader(), FileWriter::FileWriter(), HeaderFileWriter::Finalise(), LanguageFileWriter::Finalise(), BaseMedia< Tbase_set >::GetSet(), GetStringWithArgs(), FileStringReader::HandlePragma(), LoadFreeTypeFont(), main(), MallocError(), NetworkExecuteLocalCommandQueue(), FileStringReader::ParseFile(), ReallocError(), ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(), RemoveFromRailBaseStation(), SettingsIniFile::ReportFileError(), SoundDriver_Win32::Start(), strecpy(), TrainController(), and LanguageFileWriter::Write().

bool HandleBootstrap | ( |  | ) |

Handle all procedures for bootstrapping OpenTTD without a base graphics set.

This requires all kinds of trickery that is needed to avoid the use of sprites from the base graphics set which are pretty interwoven.

Returns
  True if a base set exists, otherwise false.

Definition at line 215 of file bootstrap_gui.cpp.

References _colour_gradient, _network_available, CheckForMissingGlyphs(), BlitterFactory::GetCurrentBlitter(), VideoDriver::GetInstance(), BaseMedia< GraphicsSet >::GetUsedSet(), InitializeUnicodeGlyphMap(), VideoDriver::MainLoop(), BaseMedia< GraphicsSet >::SetSet(), and usererror().

Referenced by openttd_main().

static void LoadIntroGame | ( | bool | load_newgrfs = `true` | ) |
| static

Load the introduction game.

Parameters

  load_newgrfs | Whether to load the NewGRFs or not.

Definition at line 320 of file openttd.cpp.

References _pause_mode, BASESET_DIR, CheckForMissingGlyphs(), CheckForMissingSprites(), COMPANY_FIRST, COMPANY_SPECTATOR, CursorVars::fix_at, GenerateWorld(), MusicDriver::GetInstance(), GWM_EMPTY, PM_UNPAUSED, ResetGRFConfig(), ResetWindowSystem(), SaveOrLoad(), SetLocalCompany(), SetupColoursAndInitialWindow(), SL_LOAD, SL_OK, and WaitTillGeneratedWorld().

Referenced by AfterNewGRFScan::OnNewGRFsScanned(), openttd_main(), and SafeLoad().

int openttd_main | ( | int | argc,
|  | char * | argv[]
| ) |  |

Main entry point for this lovely game.

Parameters

  argc | The number of arguments passed to this game.
  argv | The values of the arguments.

Returns
  0 when there is no error.

Definition at line 535 of file openttd.cpp.

References _blitter_autodetected, _config_file, _cur_resolution, _ini_blitter, _ini_musicdriver, _ini_sounddriver, _ini_videodriver, _load_check_data, _log_fd, _modal_progress_paint_mutex, _modal_progress_work_mutex, _network_available, _switch_mode, TarScanner::BASESET, ThreadMutex::BeginCritical(), BLT_8BPP, CheckForMissingGlyphs(), ClampU(), LoadCheckData::Clear(), DEBUG, AfterNewGRFScan::dedicated_host, AfterNewGRFScan::dedicated_port, DeterminePaths(), TarScanner::DoScan(), Driver::DT_MUSIC, Driver::DT_SOUND, Driver::DT_VIDEO, LoadCheckData::error, LoadCheckData::error_data, BaseMedia< GraphicsSet >::FindSets(), BaseMedia< SoundsSet >::FindSets(), BaseMedia< MusicSet >::FindSets(), FiosGetSavegameListCallback(), free(), GENERATE_NEW_SEED, GenerateWorld(), AfterNewGRFScan::generation_seed, VideoDriver::GetInstance(), GetOptData::GetOpt(), BaseMedia< GraphicsSet >::GetUsedSet(), GWM_EMPTY, HandleBootstrap(), LoadCheckData::HasErrors(), CursorVars::in_window, BaseMedia< SoundsSet >::ini_set, BaseMedia< MusicSet >::ini_set, BaseMedia< GraphicsSet >::ini_set, InitFreeType(), InitializeLanguagePacks(), InitializeScreenshotFormats(), InitializeSpriteSorter(), InitWindowSystem(), AfterNewGRFScan::join_company_password, AfterNewGRFScan::join_server_password, lastof, LoadFromConfig(), LoadIntroGame(), VideoDriver::MainLoop(), SmallFiosItem::mode, SmallFiosItem::name, AfterNewGRFScan::network_conn, NETWORK_DEFAULT_DEBUGLOG_PORT, NetworkStartUp(), GetOptData::numleft, GetOptData::opt, ParseConnectionString(), ParseResolution(), S8BPP_NONE, AfterNewGRFScan::save_config, SAVE_DIR, SaveHotkeysToConfig(), SaveOrLoad(), WindowDesc::SaveToConfig(), SaveToConfig(), SaveToHighScore(), ScanNewGRFFiles(), ScheduleErrorMessage(), BlitterFactory::SelectBlitter(), DriverFactoryBase::SelectDriver(), SetDebugString(), ErrorMessageData::SetDParamStr(), SetDParamStr(), BaseMedia< MusicSet >::SetSet(), BaseMedia< SoundsSet >::SetSet(), BaseMedia< GraphicsSet >::SetSet(), ShowHelp(), ShutdownGame(), SL_LOAD, SL_LOAD_CHECK, SL_OK, SLD_LOAD_GAME, SM_EDITOR, SM_LOAD_GAME, SM_LOAD_SCENARIO, SM_MENU, SM_NEWGAME, AfterNewGRFScan::startyear, strecpy(), stredup(), StrEmpty(), usererror(), WaitTillGeneratedWorld(), and ZOOM_LVL_NORMAL.

static void ParseResolution | ( | Dimension * | res,
|  | const char * | s
| ) |  |
| static

Extract the resolution from the given string and store it in the 'res' parameter.

Parameters

  res | variable to store the resolution in.
  s | the string to decompose.

Definition at line 266 of file openttd.cpp.

References max(), and ShowInfoF().

Referenced by openttd_main().

bool SafeLoad | ( | const char * | filename,
|  | int | mode,
|  | GameMode | newgm,
|  | Subdirectory | subdir,
|  | struct LoadFilter * | lf = `NULL`
| ) |  |

Load the specified savegame but on error do different things.

If loading fails due to corrupt savegame, bad version, etc. go back to a previous correct state. In the menu for example load the intro game again.

Parameters

  mode | mode of loading, either SL_LOAD or SL_OLD_LOAD
  newgm | switch to this mode of loading fails due to some unknown error
  filename | file to be loaded
  subdir | default directory to look for filename, set to 0 if not needed
  lf | Load filter to use, if NULL: use filename + subdir.

Definition at line 1000 of file openttd.cpp.

References _network_dedicated, _network_server, DEBUG, LoadIntroGame(), LoadWithFilter(), NetworkDisconnect(), SaveOrLoad(), SL_LOAD, SL_OK, SL_OLD_LOAD, and SL_REINIT.

Referenced by VideoDriver_Dedicated::MainLoop(), and ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE().

void CDECL ShowInfoF | ( | const char * | str,
|  |  | ...
| ) |  |

Shows some information on the console/a popup box depending on the OS.

Parameters

  str | the text to show.

Definition at line 130 of file openttd.cpp.

References lastof, and vseprintf().

Referenced by CheckExternalFiles(), GetFontByFaceName(), GetKeyboardLayout(), LoadFreeTypeFont(), ParseResolution(), IniFile::ReportFileError(), and SetDebugString().

static void ShutdownGame | ( |  | ) |
| static

Unitializes drivers, frees allocated memory, cleans pools, ...

Generally, prepares the game for shutting down

Definition at line 283 of file openttd.cpp.

References _config_file, _network_available, PoolBase::Clean(), LinkGraphSchedule::Clear(), FioCloseAll(), free(), GamelogReset(), NetworkShutDown(), PT_ALL, ResetNewGRFData(), DriverFactoryBase::ShutdownDrivers(), UninitFreeType(), Game::Uninitialize(), AI::Uninitialize(), and UnInitWindowSystem().

Referenced by openttd_main().

void StateGameLoop | ( |  | ) |

State controlling game loop.

The state must not be changed from anywhere but here. That check is enforced in DoCommand.

Definition at line 1340 of file openttd.cpp.

References _current_company, _date, _date_fract, _pause_mode, _settings_game, AnimateAnimatedTiles(), AUTOSAVE_DIR, CallWindowTickEvent(), CheckCaches(), GameSettings::game_creation, Game::GameLoop(), AI::GameLoop(), GameCreationSettings::generation_seed, HasModalProgress(), IncreaseDate(), IsLocalCompany(), lastof, OWNER_NONE, PM_UNPAUSED, PSM_ENTER_GAMELOOP, PSM_LEAVE_GAMELOOP, Layouter::ReduceLineCache(), Backup< T >::Restore(), RunTileLoop(), SaveOrLoad(), seprintf(), SL_SAVE, BasePersistentStorageArray::SwitchMode(), and UpdateLandscapingLimits().

Referenced by ClientNetworkGameSocketHandler::GameLoop().

void CDECL usererror | ( | const char * | s,
|  |  | ...
| ) |  |

Error handling for fatal user errors.

Parameters

  s | the string to print.

Note
  Does NEVER return.

Definition at line 90 of file openttd.cpp.

References VideoDriver::GetInstance(), lastof, Driver::Stop(), and vseprintf().

Referenced by FioOpenFile(), FreeTypeFontCache::GetGlyph(), HandleBootstrap(), HandleInvalidSpriteRequest(), InitializeLanguagePacks(), LoadGrfFile(), LoadGrfFileIndexed(), LoadNewGRFFile(), LoadNextSprite(), VideoDriver_Win32::MakeWindow(), openttd_main(), ReadSprite(), DriverFactoryBase::SelectDriver(), DriverFactoryBase::SelectDriverImpl(), ServerNetworkGameSocketHandler::SendMap(), and SwitchNewGRFBlitter().

## Variable Documentation

const OptionData _options[]
| static

Initial value:
{
GETOPT_SHORT_VALUE('I'),
GETOPT_SHORT_VALUE('S'),
GETOPT_SHORT_VALUE('M'),
GETOPT_SHORT_VALUE('m'),
GETOPT_SHORT_VALUE('s'),
GETOPT_SHORT_VALUE('v'),
GETOPT_SHORT_VALUE('b'),
GETOPT_SHORT_OPTVAL('D'),
GETOPT_SHORT_OPTVAL('n'),
GETOPT_SHORT_VALUE('l'),
GETOPT_SHORT_VALUE('p'),
GETOPT_SHORT_VALUE('P'),
GETOPT_SHORT_NOVAL('f'),
GETOPT_SHORT_VALUE('r'),
GETOPT_SHORT_VALUE('t'),
GETOPT_SHORT_OPTVAL('d'),
GETOPT_SHORT_NOVAL('e'),
GETOPT_SHORT_OPTVAL('g'),
GETOPT_SHORT_VALUE('G'),
GETOPT_SHORT_VALUE('c'),
GETOPT_SHORT_NOVAL('x'),
GETOPT_SHORT_VALUE('q'),
GETOPT_SHORT_NOVAL('h'),
}

Options of OpenTTD.

Definition at line 498 of file openttd.cpp.