82 #include <system_error>
87 # include <emscripten.h>
88 # include <emscripten/html5.h>
91 void CallLandscapeTick();
92 void DoPaletteAnimations();
99 extern void OSOpenBrowser(
const std::string &url);
100 extern void ShowOSErrorBox(
const char *buf,
bool system);
103 bool _save_config =
false;
104 bool _request_newgrf_scan =
false;
114 ShowOSErrorBox(str.c_str(),
false);
117 #ifdef __EMSCRIPTEN__
118 emscripten_exit_pointerlock();
122 EM_ASM(
if (window[
"openttd_abort"]) openttd_abort());
136 ShowOSErrorBox(str.c_str(),
true);
152 std::back_insert_iterator<std::string> output_iterator = std::back_inserter(str);
153 fmt::format_to(output_iterator,
"OpenTTD {}\n", _openttd_revision);
157 "Command line options:\n"
158 " -v drv = Set video driver (see below)\n"
159 " -s drv = Set sound driver (see below)\n"
160 " -m drv = Set music driver (see below)\n"
161 " -b drv = Set the blitter to use (see below)\n"
162 " -r res = Set resolution (for instance 800x600)\n"
163 " -h = Display this help text\n"
164 " -t year = Set starting year\n"
165 " -d [[fac=]lvl[,...]]= Debug mode\n"
166 " -e = Start Editor\n"
167 " -g [savegame|scenario|heightmap] = Start new/savegame/scenario/heightmap immediately\n"
168 " -G seed = Set random seed\n"
169 " -n host[:port][#company]= Join network game\n"
170 " -p password = Password to join server\n"
171 " -D [host][:port] = Start dedicated server\n"
173 " -f = Fork into the background (dedicated only)\n"
175 " -I graphics_set = Force the graphics set (see below)\n"
176 " -S sounds_set = Force the sounds set (see below)\n"
177 " -M music_set = Force the music set (see below)\n"
178 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
179 " -x = Never save configuration changes to disk\n"
180 " -X = Don't use global folders to search for files\n"
181 " -q savegame = Write some information about the savegame and exit\n"
182 " -Q = Don't scan for/load NewGRF files on startup\n"
183 " -QQ = Disable NewGRF scanning/loading entirely\n"
217 fmt::print(
"{}\n", str);
223 static void WriteSavegameInfo(
const std::string &name)
226 uint32_t last_ottd_rev = 0;
227 uint8_t ever_modified = 0;
228 bool removed_newgrfs =
false;
230 _gamelog.
Info(&last_ottd_rev, &ever_modified, &removed_newgrfs);
233 message.reserve(1024);
234 fmt::format_to(std::back_inserter(message),
"Name: {}\n", name);
235 fmt::format_to(std::back_inserter(message),
"Savegame ver: {}\n",
_sl_version);
236 fmt::format_to(std::back_inserter(message),
"NewGRF ver: 0x{:08X}\n", last_ottd_rev);
237 fmt::format_to(std::back_inserter(message),
"Modified: {}\n", ever_modified);
239 if (removed_newgrfs) {
240 fmt::format_to(std::back_inserter(message),
"NewGRFs have been removed\n");
243 message +=
"NewGRFs:\n";
246 fmt::format_to(std::back_inserter(message),
"{:08X} {} {}\n",
BSWAP32(c->ident.grfid),
254 fmt::print(
"{}\n", message);
269 const char *t = strchr(s,
'x');
271 ShowInfo(
"Invalid resolution '{}'", s);
275 res->width = std::max(std::strtoul(s,
nullptr, 0), 64UL);
276 res->height = std::max(std::strtoul(t + 1,
nullptr, 0), 64UL);
317 _game_mode = GM_MENU;
342 void MakeNewgameSettingsLive()
370 void OpenBrowser(
const std::string &url)
373 if (url.starts_with(
"http://") || url.starts_with(
"https://")) {
474 extern void DedicatedFork();
484 std::vector<OptionData> options;
486 for (
char c :
"GIMSbcmnpqrstv") options.push_back({ .type =
ODF_HAS_VALUE, .id = c, .shortname = c });
488 options.push_back({ .type =
ODF_HAS_VALUE, .id =
'f', .shortname =
'f' });
492 for (
char c :
"Ddg") options.push_back({ .type =
ODF_OPTIONAL_VALUE, .id = c, .shortname = c });
495 for (
char c :
"QXehx") options.push_back({ .type =
ODF_NO_VALUE, .id = c, .shortname = c });
509 std::string musicdriver;
510 std::string sounddriver;
511 std::string videodriver;
513 std::string graphics_set;
514 std::string sounds_set;
515 std::string music_set;
517 std::unique_ptr<AfterNewGRFScan> scanner = std::make_unique<AfterNewGRFScan>();
518 bool dedicated =
false;
519 bool only_local_path =
false;
521 extern bool _dedicated_forks;
522 _dedicated_forks =
false;
524 _game_mode = GM_MENU;
528 GetOptData mgo(arguments.subspan(1), options);
532 while ((i = mgo.
GetOpt()) != -1) {
534 case 'I': graphics_set = mgo.
opt;
break;
535 case 'S': sounds_set = mgo.
opt;
break;
536 case 'M': music_set = mgo.
opt;
break;
537 case 'm': musicdriver = mgo.
opt;
break;
538 case 's': sounddriver = mgo.
opt;
break;
539 case 'v': videodriver = mgo.
opt;
break;
540 case 'b': blitter = mgo.
opt;
break;
542 musicdriver =
"null";
543 sounddriver =
"null";
544 videodriver =
"dedicated";
548 if (mgo.
opt !=
nullptr) {
552 case 'f': _dedicated_forks =
true;
break;
554 scanner->connection_string = mgo.
opt;
557 scanner->join_server_password = mgo.
opt;
560 case 't': scanner->startyear = atoi(mgo.
opt);
break;
578 if (mgo.
opt !=
nullptr) {
583 if (ft == FIOS_TYPE_INVALID) {
586 if (ft == FIOS_TYPE_INVALID) {
605 scanner->generation_seed = InteractiveRandom();
615 std::string extension =
FS2OTTD(std::filesystem::path(
OTTD2FS(mgo.
opt)).extension());
621 fmt::print(stderr,
"Failed to open savegame\n");
630 WriteSavegameInfo(title);
638 case 'G': scanner->generation_seed = std::strtoul(mgo.
opt,
nullptr, 10);
break;
640 case 'x': scanner->save_config =
false;
break;
641 case 'X': only_local_path =
true;
break;
667 if (dedicated)
Debug(net, 3,
"Starting dedicated server, version {}", _openttd_revision);
668 if (_dedicated_forks && !dedicated) _dedicated_forks =
false;
672 if (_dedicated_forks) DedicatedFork();
702 bool valid_graphics_set;
703 if (!graphics_set.empty()) {
705 }
else if (BaseGraphics::ini_data.shortname != 0) {
706 graphics_set = BaseGraphics::ini_data.name;
708 if (valid_graphics_set && !BaseGraphics::ini_data.extra_params.empty()) {
711 extra_cfg.SetParams(BaseGraphics::ini_data.extra_params);
714 }
else if (!BaseGraphics::ini_data.name.empty()) {
715 graphics_set = BaseGraphics::ini_data.name;
718 valid_graphics_set =
true;
721 if (!valid_graphics_set) {
724 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
732 Debug(misc, 1,
"Loading blitter...");
746 UserError(
"Failed to autoprobe blitter") :
747 UserError(
"Failed to select requested blitter '{}'; does it exist?", blitter);
779 UserError(
"Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
781 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
791 UserError(
"Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
793 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
817 void HandleExitGameRequest()
819 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) {
860 static void MakeNewGameDone()
902 static void MakeNewGame(
bool from_heightmap,
bool reset_settings)
904 _game_mode = GM_NORMAL;
905 if (!from_heightmap) {
916 static void MakeNewEditorWorldDone()
921 static void MakeNewEditorWorld()
923 _game_mode = GM_EDITOR;
952 if (result ==
SL_OK)
return true;
961 Debug(net, 0,
"Loading requested map failed; closing server.");
980 Debug(net, 0,
"Loading game failed, so a new (random) game will be started");
981 MakeNewGame(
false,
true);
993 case GM_EDITOR: MakeNewEditorWorld();
break;
998 static void UpdateSocialIntegration(
GameMode game_mode)
1000 switch (game_mode) {
1040 MakeNewgameSettingsLive();
1043 NetworkServerStart();
1068 MakeNewEditorWorld();
1071 UpdateSocialIntegration(GM_EDITOR);
1090 UpdateSocialIntegration(GM_NORMAL);
1098 UpdateSocialIntegration(GM_NORMAL);
1116 UpdateSocialIntegration(GM_NORMAL);
1125 UpdateSocialIntegration(GM_NORMAL);
1131 _game_mode = GM_EDITOR;
1137 UpdateSocialIntegration(GM_EDITOR);
1151 UpdateSocialIntegration(GM_EDITOR);
1170 static bool asked_once =
false;
1177 UpdateSocialIntegration(GM_MENU);
1201 default: NOT_REACHED();
1229 #ifndef DEBUG_DUMP_COMMANDS
1240 if (_game_mode == GM_EDITOR) {
1244 CallLandscapeTick();
1272 CallLandscapeTick();
1275 #ifndef DEBUG_DUMP_COMMANDS
1333 if (_request_newgrf_scan)
return false;
1335 _request_newgrf_scan =
true;
1336 _request_newgrf_scan_callback = callback;
1342 if (_game_mode == GM_BOOTSTRAP) {
1348 if (_request_newgrf_scan) {
1350 _request_newgrf_scan =
false;
1351 _request_newgrf_scan_callback =
nullptr;
1353 if (_exit_game)
return;
1358 if (_game_mode == GM_NORMAL) {
1359 static auto last_time = std::chrono::steady_clock::now();
1360 auto now = std::chrono::steady_clock::now();
1361 auto delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_time);
1362 if (delta_ms.count() != 0) {
1372 if (_exit_game)
return;
1375 IncreaseSpriteLRU();
Base functions for all AIs.
AIConfig stores the configuration settings of every AI.
void AnimateAnimatedTiles()
Animate all tiles in the animated tile list, i.e. call AnimateTile on them.
Class for backupping variables and making sure they are restored later.
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
static void Uninitialize(bool keepConfig)
Uninitialize the AI system.
static void Initialize()
Initialize the AI system.
static void GetConsoleList(std::back_insert_iterator< std::string > &output_iterator, bool newest_only)
Wrapper function for AIScanner::GetAIConsoleList.
static void GameLoop()
Called every game-tick to let AIs do something.
static void KillAll()
Kill any and all AIs we manage.
static std::string ini_set
The set as saved in the config file.
static std::string ini_set
The set as saved in the config file.
static Blitter * SelectBlitter(const std::string_view name)
Find the requested blitter and return its class.
static void GetBlittersInfo(std::back_insert_iterator< std::string > &output_iterator)
Fill a buffer with information about the blitters.
static void SetErrorMessage(const std::string &message)
Sets a message for the error message handler.
static void ShutdownDrivers()
Shuts down all active drivers.
static void SelectDriver(const std::string &name, Driver::Type type)
Find the requested driver and return its class.
static void GetDriversInfo(std::back_insert_iterator< std::string > &output_iterator)
Build a human readable list of available drivers, grouped by type.
virtual void Stop()=0
Stop this driver.
@ DT_VIDEO
A video driver.
@ DT_SOUND
A sound driver.
@ DT_MUSIC
A music driver, needs to be before sound to properly shut down extmidi forked music players.
The data of the error message.
void SetDParamStr(uint n, const char *str)
Set a rawstring parameter.
static void GameLoop()
Called every game-tick to let Game do something.
static void GetConsoleList(std::back_insert_iterator< std::string > &output_iterator, bool newest_only)
Wrapper function for GameScanner::GetConsoleList.
static void Uninitialize(bool keepConfig)
Uninitialize the Game system.
static void Initialize()
Initialize the Game system.
void Info(uint32_t *last_ottd_rev, uint8_t *ever_modified, bool *removed_newgrfs)
Get some basic information from the given gamelog.
void Reset()
Resets and frees all memory allocated - used before loading or starting a new game.
An interval timer will fire every interval, and will continue to fire until it is deleted.
static void ReduceLineCache()
Reduce the size of linecache if necessary to prevent infinite growth.
static void Clear()
Clear all link graphs and jobs from the schedule.
static MusicDriver * GetInstance()
Get the currently active instance of the music driver.
virtual void SetVolume(uint8_t vol)=0
Set the volume, if possible.
@ EXIT
User is exiting the application.
@ LEAVE
User is leaving the game (but not exiting the application).
void Transmit(Reason reason, bool blocking=false)
Transmit the survey.
static void EventEnterScenarioEditor(uint map_width, uint map_height)
Event: user entered the Scenario Editor.
static void EventEnterSingleplayer(uint map_width, uint map_height)
Event: user entered a singleplayer game.
static void RunCallbacks()
Allow any social integration library to handle their own events.
static void EventEnterMultiplayer(uint map_width, uint map_height)
Event: user entered a multiplayer game.
static void Shutdown()
Shutdown the social integration system, and all social integration plugins that are loaded.
static void EventEnterMainMenu()
Event: user entered the main menu.
static void EventJoiningMultiplayer()
Event: user is joining a multiplayer game.
static void Initialize()
Initialize the social integration system, loading any social integration plugins that are available.
virtual void MainLoop()
Called once every tick.
static SoundDriver * GetInstance()
Get the currently active instance of the sound driver.
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
@ BASESET
Scan for base sets.
@ SCENARIO
Scan for scenarios and heightmaps.
static Year year
Current year, starting at 0.
static constexpr TimerGame< struct Calendar >::Year INVALID_YEAR
Representation of an invalid year.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static DateFract date_fract
Fractional part of the day.
@ AUTOSAVE
Only run when not paused or there was a Command executed recently.
The TimerManager manages a single Timer-type.
static bool Elapsed(TElapsed value)
Called when time for this timer elapsed.
virtual void MainLoop()=0
Perform the actual drawing.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Functions related to commands.
Colours _company_colours[MAX_COMPANIES]
NOSAVE: can be determined from company structs.
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
void UpdateLandscapingLimits()
Update the landscaping limits per company.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
CompanyID _current_company
Company currently doing an action.
Command definitions related to companies.
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
Owner
Enum for all companies/owners.
@ INVALID_COMPANY
An invalid company.
@ COMPANY_SPECTATOR
The client is spectating.
@ COMPANY_FIRST
First company, same as owner.
@ OWNER_NONE
The tile has no ownership.
@ COMPANY_NEW_COMPANY
The client wants a new company.
@ MAX_COMPANIES
Maximum number of companies.
void IConsoleCmdExec(const std::string &command_string, const uint recurse_count)
Execute a given command passed to us.
Console functions used outside of the console code.
Functions to be called to log a crash.
void SetDebugString(const char *s, void(*error_func)(const std::string &))
Set debugging levels by parsing the text in s.
void DumpDebugFacilityNames(std::back_insert_iterator< std::string > &output_iterator)
Dump the available debug facility names in the help text.
void DebugSendRemoteMessages()
Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the GameLoop threa...
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
std::string _ini_videodriver
The video driver a stored in the configuration file.
std::string _ini_musicdriver
The music driver a stored in the configuration file.
Dimension _cur_resolution
The current resolution.
std::string _ini_sounddriver
The sound driver a stored in the configuration file.
void SettingsDisableElrail(int32_t new_value)
_settings_game.disable_elrail callback
header file for electrified rail specific functions
void CheckEngines()
Check for engines that have an appropriate availability.
Functions related to engines.
Functions related to errors.
void ScheduleErrorMessage(ErrorList &datas)
Schedule a list of errors.
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
@ WL_ERROR
Errors (eg. saving/loading failed)
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Error reporting related functions.
Factory to 'query' all available blitters.
bool _blitter_autodetected
Was the blitter autodetected or specified by the user?
std::string _ini_blitter
The blitter as stored in the configuration file.
void DeterminePaths(const char *exe, bool only_local_path)
Acquire the base paths (personal dir and game data dir), fill all other paths (save dir,...
DetailedFileType GetDetailedFileType(FiosType fios_type)
Extract the detailed file type from a FiosType.
AbstractFileType GetAbstractFileType(FiosType fios_type)
Extract the abstract file type from a FiosType.
@ FT_SCENARIO
old or new scenario
@ FT_HEIGHTMAP
heightmap file
@ FT_SAVEGAME
old or new savegame
@ FT_INVALID
Invalid or unknown file type.
SaveLoadOperation
Operation performed on the file.
@ SLO_CHECK
Load file for checking and/or preview.
@ SLO_SAVE
File is being saved.
@ SLO_LOAD
File is being loaded.
@ SLO_INVALID
Unknown file operation.
DetailedFileType
Kinds of files in each AbstractFileType.
@ DFT_GAME_FILE
Save game or scenario file.
@ DFT_INVALID
Unknown or invalid file.
@ DFT_OLD_GAME_FILE
Old save game or scenario file.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
@ NO_DIRECTORY
A path without any base directory.
@ SAVE_DIR
Base directory for all savegames.
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
std::tuple< FiosType, std::string > FiosGetSavegameListCallback(SaveLoadOperation fop, const std::string &file, const std::string_view ext)
Callback for FiosGetFileList.
std::tuple< FiosType, std::string > FiosGetScenarioListCallback(SaveLoadOperation fop, const std::string &file, const std::string_view ext)
Callback for FiosGetFileList.
Declarations for savegames operations.
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
void InitFontCache(bool monospace)
(Re)initialize the font cache related things, i.e.
void UninitFontCache()
Free everything allocated w.r.t.
Functions to read fonts from files and cache them.
Types for recording game performance data.
@ PFE_GAMELOOP
Speed of gameloop processing.
@ PFE_GL_SHIPS
Time spent processing ships.
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
@ PFE_GL_ECONOMY
Time spent processing cargo movement.
@ PFE_GL_LANDSCAPE
Time spent processing other world features.
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
@ PFE_GL_TRAINS
Time spent processing trains.
@ PFE_ALLSCRIPTS
Sum of all GS/AI scripts.
Base functions for all Games.
GameConfig stores the configuration settings of every Game.
SaveLoadVersion _sl_version
the major savegame version identifier
Gamelog _gamelog
Gamelog instance.
Functions to be called to log fundamental changes to the game.
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done.
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
Functions related to world/map generation.
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
@ GWM_EMPTY
Generate an empty map (sea-level)
@ GWM_RANDOM
Generate a random map for SE.
@ GWM_NEWGAME
Generate a map for a new game.
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
Library for parsing command-line options.
@ ODF_OPTIONAL_VALUE
An option with an optional value.
@ ODF_NO_VALUE
A plain option (no value attached to it).
@ ODF_HAS_VALUE
An option with a value.
PauseMode _pause_mode
The current pause mode.
GameSessionStats _game_session_stats
Statistics about the current session.
void UpdateGUIZoom()
Resolve GUI zoom level, if auto-suggestion is requested.
SwitchMode _switch_mode
The next mainloop command.
Functions related to laying out the texts.
@ S8BPP_NONE
No support for 8bpp by OS or hardware, force 32bpp blitters.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
GUI functions that shouldn't be here.
void LoadFromHighScore()
Initialize the highscore table to 0 and if any file exists, load in values.
void SaveToHighScore()
Save HighScore table to file.
Declaration of functions and types defined in highscore.h and highscore_gui.h.
void LoadHotkeysFromConfig()
Load the hotkeys from the config file.
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
Hotkey related functions.
void CheckIndustries()
Verify whether the generated industries are complete, and warn the user if not.
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every TILE_UPDATE_FREQU...
void StateGameLoop_LinkGraphPauseControl()
Pause the game if in 2 TimerGameEconomy::date_fract ticks, we would do a join with the next link grap...
Declaration of link graph schedule used for cargo distribution.
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
void GenerateSavegameId()
Generate an unique savegame ID.
Miscellaneous command definitions.
Functions to mix sound samples.
Base for all music playback.
void NetworkStartUp()
This tries to launch the network for a given OS.
bool _is_network_server
Does this client wants to be a network-server?
void NetworkClientJoinGame()
Actually perform the joining to the server.
void NetworkOnGameStart()
Perform tasks when the server is started.
bool _network_available
is network mode available?
uint8_t _network_reconnect
Reconnect timeout.
bool _networking
are we in networking mode?
std::string_view ParseFullConnectionString(const std::string &connection_string, uint16_t &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
bool _network_dedicated
are we a dedicated server?
void NetworkDisconnect(bool close_admins)
We want to disconnect from the host/clients.
bool _network_server
network-server is active
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
StringList _network_bind_list
The addresses to bind on.
bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password)
Join a client to the server at with the given connection string.
void NetworkShutDown()
This shuts the network down.
Basic functions/variables used all over the place.
Network functions used by other parts of OpenTTD.
void ShowNetworkAskSurvey()
Show a modal confirmation window with "no" / "preview" / "yes" buttons.
GUIs related to networking.
Part of the network protocol handling opt-in survey.
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
void ResetNewGRFData()
Reset all NewGRF loaded data.
Base for the NewGRF implementation.
void UpdateNewGRFConfigPalette(int32_t)
Update the palettes of the graphics from the config file.
void ResetGRFConfig(bool defaults)
Reset the current GRF Config to either blank or newgame settings.
void ScanNewGRFFiles(NewGRFScanCallback *callback)
Scan for all NewGRFs.
int _skip_all_newgrf_scanning
Set this flag to prevent any NewGRF scanning from being done.
@ GCF_COMPATIBLE
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches)
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
@ PSM_LEAVE_GAMELOOP
Leave the gameloop, changes will be temporary.
Functions related to news.
void MusicLoop()
Check music playback status and start/stop/song-finished.
void FatalErrorI(const std::string &str)
Error handling for fatal non-user errors.
static void OnStartScenario()
Triggers everything required to set up a saved scenario for a new game.
int openttd_main(std::span< char *const > arguments)
Main entry point for this lovely game.
static void ParseResolution(Dimension *res, const char *s)
Extract the resolution from the given string and store it in the 'res' parameter.
static void OnStartGame(bool dedicated_server)
Triggers everything that should be triggered when starting a game.
bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, std::shared_ptr< LoadFilter > lf=nullptr)
Load the specified savegame but on error do different things.
void ChangeAutosaveFrequency(bool reset)
Reset the interval of the autosave.
void StateGameLoop()
State controlling game loop.
void UserErrorI(const std::string &str)
Error handling for fatal user errors.
static std::vector< OptionData > CreateOptions()
Create all the options that OpenTTD supports.
Company * DoStartupNewCompany(bool is_ai, CompanyID company=INVALID_COMPANY)
Create a new company and sets all company variables default values.
static void ShowHelp()
Show the help message when someone passed a wrong parameter.
bool RequestNewGRFScan(NewGRFScanCallback *callback)
Request a new NewGRF scan.
static void ShutdownGame()
Uninitializes drivers, frees allocated memory, cleans pools, ...
static void LoadIntroGame(bool load_newgrfs=true)
Load the introduction game.
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
void CheckCaches()
Check the validity of some of the caches.
std::string _config_file
Configuration file of OpenTTD.
bool HandleBootstrap()
Handle all procedures for bootstrapping OpenTTD without a base graphics set.
static IntervalTimer< TimerGameRealtime > _autosave_interval({std::chrono::milliseconds::zero(), TimerGameRealtime::AUTOSAVE}, [](auto) { _pause_mode &=~PM_COMMAND_DURING_PAUSE;_do_autosave=true;SetWindowDirty(WC_STATUS_BAR, 0);static FiosNumberedSaveName _autosave_ctr("autosave");DoAutoOrNetsave(_autosave_ctr);_do_autosave=false;SetWindowDirty(WC_STATUS_BAR, 0);})
Interval for regular autosaves.
SwitchMode
Mode which defines what mode we're switching to.
@ SM_START_HEIGHTMAP
Load a heightmap and start a new game from it.
@ SM_RESTART_HEIGHTMAP
Load a heightmap and start a new game from it with current settings.
@ SM_LOAD_SCENARIO
Load scenario from scenario editor.
@ SM_GENRANDLAND
Generate random land within scenario editor.
@ SM_JOIN_GAME
Join a network game.
@ SM_MENU
Switch to game intro menu.
@ SM_RESTARTGAME
Restart --> 'Random game' with current settings.
@ SM_RELOADGAME
Reload the savegame / scenario / heightmap you started the game with.
@ SM_SAVE_HEIGHTMAP
Save heightmap.
@ SM_LOAD_HEIGHTMAP
Load heightmap from scenario editor.
@ SM_LOAD_GAME
Load game, Play Scenario.
@ SM_EDITOR
Switch to scenario editor.
@ SM_NEWGAME
New Game --> 'Random game'.
@ PM_COMMAND_DURING_PAUSE
A game paused, and a command executed during the pause; resets on autosave.
@ PM_UNPAUSED
A normal unpaused game.
@ PM_PAUSED_NORMAL
A game normally paused.
@ PM_PAUSED_SAVELOAD
A game paused for saving/loading.
GameMode
Mode which defines the state of the game.
@ DO_FULL_ANIMATION
Perform palette animation.
Functions related to modal progress.
bool HasModalProgress()
Check if we are currently in a modal progress state.
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
Pseudo random number generator.
declaration of OTTD revision dependent variables
void InitializeRoadGUI()
I really don't know why rail_gui.cpp has this too, shouldn't be included in the other one?
Functions/types related to the road GUIs.
Base class for roadstops.
A number of safeguards to prevent using unsafe methods.
void ProcessAsyncSaveFinish()
Handle async save finishes.
StringID GetSaveLoadErrorMessage()
Return the description of the error.
SaveOrLoadResult LoadWithFilter(std::shared_ptr< LoadFilter > reader)
Load the game using a (reader) filter.
bool _do_autosave
are we doing an autosave at the moment?
StringID GetSaveLoadErrorType()
Return the appropriate initial string for an error depending on whether we are saving or loading.
SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Functions/types related to saving and loading games.
SaveOrLoadResult
Save or load result codes.
@ SL_OK
completed successfully
@ SL_REINIT
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
bool MakeHeightmapScreenshot(const char *filename)
Make a heightmap of the current map.
void InitializeScreenshotFormats()
Initialize screenshot format information on startup, with _screenshot_format_name filled from the loa...
Functions to make screenshots.
void LoadFromConfig(bool startup)
Load the values from the configuration files.
void SaveToConfig()
Save the values to the configuration file.
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
ClientSettings _settings_client
The current settings for this game.
Functions related to setting/changing the settings.
Interface definitions for game to report/respond to social integration.
Base for all sound drivers.
Base classes/functions for stations.
Definition of base types and functions in a cross-platform compatible way.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
bool StrEmpty(const char *s)
Check if a string buffer is empty.
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
void InitializeLanguagePacks()
Make a list of the available language packs.
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Functions related to OTTD's strings.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Callback structure of statements to be executed after the NewGRF scan.
std::string dedicated_host
Hostname for the dedicated server.
TimerGameCalendar::Year startyear
The start year.
void OnNewGRFsScanned() override
Called whenever the NewGRF scan completed.
uint16_t dedicated_port
Port for the dedicated server.
bool save_config
The save config setting.
std::string connection_string
Information about the server to connect to.
uint32_t generation_seed
Seed for the new game.
std::string join_server_password
The password to join the server with.
AfterNewGRFScan()
Create a new callback.
Class to backup a specific variable and restore it later.
void Restore()
Restore the variable.
uint32_t extra_version
version of the extra GRF
static void SwitchMode(PersistentStorageMode mode, bool ignore_prev_mode=false)
Clear temporary changes made since the last call to SwitchMode, and set whether subsequent changes sh...
std::string name
The name of the base set.
CompanySettings company
default values for per-company settings
MusicSettings music
settings related to music/sound
NetworkSettings network
settings related to the network
GUISettings gui
settings related to the GUI
CompanySettings settings
settings specific for each company
Colours colour
Company colour.
VehicleDefaultSettings vehicle
default settings for vehicles
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
bool in_window
mouse inside this window, determines drawing logic
Dimensions (a width and height) of a rectangle in 2D.
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
void SetMode(FiosType ft)
Set the mode and file type of the file to save or load based on the type of file entry at the file sy...
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
SaveLoadOperation file_op
File operation to perform.
std::string name
Name of the file.
A savegame name automatically numbered.
Information about GRF, used in the game and (part of it) in savegames.
struct GRFConfig * next
NOSAVE: Next item in the linked list.
bool IsCompatible(uint32_t old_version) const
Return whether this NewGRF can replace an older version of the same NewGRF.
uint64_t used_liveries
Bitmask of LiveryScheme used by the defined engines.
uint32_t last_newgrf_count
the numbers of NewGRFs we found during the last scan
Colours starting_colour_secondary
default secondary color scheme for the company to start a new game with
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?...
bool pause_on_newgame
whether to start new games paused or not
uint32_t autosave_interval
how often should we do autosaves?
Colours starting_colour
default color scheme for the company to start a new game with
uint8_t map_x
X size of map.
uint8_t map_y
Y size of map.
TimerGameCalendar::Year starting_year
starting date
uint32_t generation_seed
noise seed for world generation
std::chrono::steady_clock::time_point start_time
Time when the current game was started.
std::optional< size_t > savegame_size
Size of the last saved savegame in bytes, or std::nullopt if not saved yet.
class AIConfig * ai_config[MAX_COMPANIES]
settings per company
class GameConfig * game_config
settings for gamescript
GameCreationSettings game_creation
settings used during the creation of a game (map)
VehicleSettings vehicle
options for vehicles
Data storage for parsing command line options.
ArgumentSpan arguments
Remaining command line arguments.
int GetOpt()
Find the next option.
const char * opt
Option value, if available (else nullptr).
GRFConfig & GetOrCreateExtraConfig() const
Return configuration for the extra GRF, or lazily create it.
Defines the internal data of a functional industry.
bool HasNewGrfs()
Check whether the game uses any NewGrfs.
std::string error_msg
Data to pass to SetDParamStr when displaying error.
StringID error
Error message from loading. INVALID_STRING_ID if no error.
GRFConfig * grfconfig
NewGrf configuration from save.
bool HasErrors()
Check whether loading the game resulted in errors.
void Clear()
Reset read data.
static uint SizeY()
Get the size of the map along the Y.
static debug_inline uint SizeX()
Get the size of the map along the X.
uint8_t effect_vol
The requested effects volume.
uint8_t music_vol
The requested music volume.
bool reload_cfg
reload the config file before restarting
uint16_t server_port
port the server listens on
std::string last_joined
Last joined server.
ParticipateSurvey participate_survey
Participate in the automated survey.
Callback for NewGRF scanning.
static void Clean(PoolType)
Clean all pools of given type.
Tindex index
Index of this pool item.
static Titem * Get(size_t index)
Returns Titem with given index.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Templated helper to make a type-safe 'typedef' representing a single POD value.
bool disable_elrails
when true, the elrails are disabled
static void SaveToConfig()
Save all WindowDesc settings to _windows_file.
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
Functions related to subsidies.
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the real time game-timer.
Definition of the tick-based game-timer.
Base for the train class.
uint8_t _display_opt
What do we want to draw/do?
void RunVehicleCalendarDayProc()
Age all vehicles, spreading out the action using the current TimerGameCalendar::date_fract.
Functions related to vehicles.
Base of all video drivers.
void InitializeSpriteSorter()
Choose the "best" sprite sorter and set _vp_sprite_sorter.
Functions related to (drawing on) viewports.
Types related to sprite sorting.
std::wstring OTTD2FS(const std::string &name)
Convert from OpenTTD's encoding to a wide string.
std::string FS2OTTD(const std::wstring &name)
Convert to OpenTTD's encoding from a wide string.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
void UnInitWindowSystem()
Close down the windowing system.
void InitWindowSystem()
(re)initialize the windowing system
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
@ WC_SAVELOAD
Saveload window; Window numbers:
@ ZOOM_LVL_MIN
Minimum zoom level.