Go to the documentation of this file.
75 #include <system_error>
80 # include <emscripten.h>
81 # include <emscripten/html5.h>
84 void CallLandscapeTick();
86 void DoPaletteAnimations();
93 extern void ShowOSErrorBox(
const char *buf,
bool system);
96 bool _save_config =
false;
97 bool _request_newgrf_scan =
false;
114 ShowOSErrorBox(buf,
false);
117 #ifdef __EMSCRIPTEN__
118 emscripten_exit_pointerlock();
122 EM_ASM(
if (window[
"openttd_syncfs"]) openttd_syncfs());
123 EM_ASM(
if (window[
"openttd_abort"]) openttd_abort());
134 void CDECL
error(
const char *s, ...)
144 ShowOSErrorBox(buf,
true);
178 "Command line options:\n"
179 " -v drv = Set video driver (see below)\n"
180 " -s drv = Set sound driver (see below)\n"
181 " -m drv = Set music driver (see below)\n"
182 " -b drv = Set the blitter to use (see below)\n"
183 " -r res = Set resolution (for instance 800x600)\n"
184 " -h = Display this help text\n"
185 " -t year = Set starting year\n"
186 " -d [[fac=]lvl[,...]]= Debug mode\n"
187 " -e = Start Editor\n"
188 " -g [savegame] = Start new/save game immediately\n"
189 " -G seed = Set random seed\n"
190 " -n [ip:port#company]= Join network game\n"
191 " -p password = Password to join server\n"
192 " -P password = Password to join company\n"
193 " -D [ip][:port] = Start dedicated server\n"
194 " -l ip[:port] = Redirect Debug()\n"
196 " -f = Fork into the background (dedicated only)\n"
198 " -I graphics_set = Force the graphics set (see below)\n"
199 " -S sounds_set = Force the sounds set (see below)\n"
200 " -M music_set = Force the music set (see below)\n"
201 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
202 " -x = Never save configuration changes to disk\n"
203 " -X = Don't use global folders to search for files\n"
204 " -q savegame = Write some information about the savegame and exit\n"
205 " -Q = Don't scan for/load NewGRF files on startup\n"
206 " -QQ = Disable NewGRF scanning/loading entirely\n"
250 static void WriteSavegameInfo(
const char *
name)
253 uint32 last_ottd_rev = 0;
254 byte ever_modified = 0;
255 bool removed_newgrfs =
false;
263 p +=
seprintf(p,
lastof(buf),
"NewGRF ver: 0x%08X\n", last_ottd_rev);
266 if (removed_newgrfs) {
275 p +=
seprintf(p,
lastof(buf),
"%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
297 const char *t = strchr(s,
'x');
303 res->width = std::max(strtoul(s,
nullptr, 0), 64UL);
304 res->height = std::max(strtoul(t + 1,
nullptr, 0), 64UL);
344 _game_mode = GM_MENU;
369 void MakeNewgameSettingsLive()
400 void OpenBrowser(
const char *url)
403 if (strstr(url,
"http://") != url && strstr(url,
"https://") != url)
return;
405 extern void OSOpenBrowser(
const char *url);
490 extern void DedicatedFork();
533 std::string musicdriver;
534 std::string sounddriver;
535 std::string videodriver;
537 std::string graphics_set;
538 std::string sounds_set;
539 std::string music_set;
542 bool dedicated =
false;
543 char *debuglog_conn =
nullptr;
544 bool only_local_path =
false;
546 extern bool _dedicated_forks;
547 _dedicated_forks =
false;
549 _game_mode = GM_MENU;
556 while ((i = mgo.
GetOpt()) != -1) {
558 case 'I': graphics_set = mgo.
opt;
break;
559 case 'S': sounds_set = mgo.
opt;
break;
560 case 'M': music_set = mgo.
opt;
break;
561 case 'm': musicdriver = mgo.
opt;
break;
562 case 's': sounddriver = mgo.
opt;
break;
563 case 'v': videodriver = mgo.
opt;
break;
564 case 'b': blitter = mgo.
opt;
break;
566 musicdriver =
"null";
567 sounddriver =
"null";
568 videodriver =
"dedicated";
572 if (mgo.
opt !=
nullptr) {
576 case 'f': _dedicated_forks =
true;
break;
578 scanner->connection_string = mgo.
opt;
581 debuglog_conn = mgo.
opt;
584 scanner->join_server_password = mgo.
opt;
587 scanner->join_company_password = mgo.
opt;
590 case 't': scanner->startyear = atoi(mgo.
opt);
break;
600 if (mgo.
opt !=
nullptr) {
608 if (t != std::string::npos) {
619 scanner->generation_seed = InteractiveRandom();
636 fprintf(stderr,
"Failed to open savegame\n");
642 fprintf(stderr,
"%s\n", buf);
647 WriteSavegameInfo(title);
655 case 'G': scanner->generation_seed = strtoul(mgo.
opt,
nullptr, 10);
break;
657 case 'x': scanner->save_config =
false;
break;
658 case 'X': only_local_path =
true;
break;
666 if (i == -2 || mgo.
numleft > 0) {
684 if (dedicated)
Debug(net, 3,
"Starting dedicated server, version {}", _openttd_revision);
685 if (_dedicated_forks && !dedicated) _dedicated_forks =
false;
689 if (_dedicated_forks) DedicatedFork();
721 if (!graphics_set.empty()) {
724 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
725 msg.SetDParamStr(0, graphics_set);
733 Debug(misc, 1,
"Loading blitter...");
747 usererror(
"Failed to autoprobe blitter") :
748 usererror(
"Failed to select requested blitter '%s'; does it exist?", blitter.c_str());
766 NetworkStartDebugLog(debuglog_conn);
783 usererror(
"Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
785 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
795 usererror(
"Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
797 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
834 void HandleExitGameRequest()
836 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) {
876 static void MakeNewGameDone()
921 static void MakeNewGame(
bool from_heightmap,
bool reset_settings)
923 _game_mode = GM_NORMAL;
924 if (!from_heightmap) {
935 static void MakeNewEditorWorldDone()
940 static void MakeNewEditorWorld()
942 _game_mode = GM_EDITOR;
971 if (result ==
SL_OK)
return true;
980 Debug(net, 0,
"Loading requested map failed; closing server.");
999 Debug(net, 0,
"Loading game failed, so a new (random) game will be started");
1000 MakeNewGame(
false,
true);
1012 case GM_EDITOR: MakeNewEditorWorld();
break;
1037 MakeNewgameSettingsLive();
1040 NetworkServerStart();
1053 MakeNewEditorWorld();
1155 default: NOT_REACHED();
1170 if (_debug_desync_level <= 1)
return;
1173 std::vector<TownCache> old_town_caches;
1175 old_town_caches.push_back(t->cache);
1184 if (
MemCmpT(old_town_caches.data() + i, &t->cache) != 0) {
1185 Debug(desync, 2,
"town cache mismatch: town {}", t->index);
1191 std::vector<CompanyInfrastructure> old_infrastructure;
1200 Debug(desync, 2,
"infrastructure cache mismatch: company {}", c->
index);
1210 rs->GetEntry(
DIAGDIR_NE)->CheckIntegrity(rs);
1211 rs->GetEntry(
DIAGDIR_NW)->CheckIntegrity(rs);
1219 for (
const Vehicle *u = v; u !=
nullptr; u = u->
Next()) length++;
1221 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1222 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1224 TrainCache *tra_cache = CallocT<TrainCache>(length);
1227 for (
const Vehicle *u = v; u !=
nullptr; u = u->
Next()) {
1229 grf_cache[length] = u->grf_cache;
1230 veh_cache[length] = u->vcache;
1254 for (
const Vehicle *u = v; u !=
nullptr; u = u->
Next()) {
1256 if (memcmp(&grf_cache[length], &u->grf_cache,
sizeof(
NewGRFCache)) != 0) {
1257 Debug(desync, 2,
"newgrf cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v->
type, v->
index, v->
owner, v->
unitnumber, length);
1259 if (memcmp(&veh_cache[length], &u->vcache,
sizeof(
VehicleCache)) != 0) {
1260 Debug(desync, 2,
"vehicle cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v->
type, v->
index, v->
owner, v->
unitnumber, length);
1265 Debug(desync, 2,
"train ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->
index, v->
owner, v->
unitnumber, length);
1268 Debug(desync, 2,
"train cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->
index, v->
owner, v->
unitnumber, length);
1273 Debug(desync, 2,
"road vehicle ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->
index, v->
owner, v->
unitnumber, length);
1292 v->cargo.InvalidateCache();
1297 std::vector<StationList> old_town_stations_near;
1298 for (
Town *t :
Town::Iterate()) old_town_stations_near.push_back(t->stations_near);
1300 std::vector<StationList> old_industry_stations_near;
1307 st->goods[c].cargo.InvalidateCache();
1313 std::map<TileIndex, bool> docking_tiles;
1314 for (
TileIndex tile : st->docking_station) {
1318 UpdateStationDockingTiles(st);
1319 if (ta.
tile != st->docking_station.tile || ta.
w != st->docking_station.w || ta.
h != st->docking_station.h) {
1320 Debug(desync, 2,
"station docking mismatch: station {}, company {}", st->index, st->owner);
1324 Debug(desync, 2,
"docking tile mismatch: tile {}", tile);
1329 IndustryList industries_near = st->industries_near;
1330 st->RecomputeCatchment();
1331 if (st->industries_near != industries_near) {
1332 Debug(desync, 2,
"station industries near mismatch: station {}", st->index);
1339 if (t->stations_near != old_town_stations_near[i]) {
1340 Debug(desync, 2,
"town stations near mismatch: town {}", t->index);
1346 if (ind->stations_near != old_industry_stations_near[i]) {
1347 Debug(desync, 2,
"industry stations near mismatch: industry {}", ind->index);
1375 #ifndef DEBUG_DUMP_COMMANDS
1386 if (_game_mode == GM_EDITOR) {
1390 CallLandscapeTick();
1399 char name[MAX_PATH];
1415 CallLandscapeTick();
1418 #ifndef DEBUG_DUMP_COMMANDS
1455 if (_request_newgrf_scan)
return false;
1457 _request_newgrf_scan =
true;
1458 _request_newgrf_scan_callback = callback;
1464 if (_game_mode == GM_BOOTSTRAP) {
1470 if (_request_newgrf_scan) {
1472 _request_newgrf_scan =
false;
1473 _request_newgrf_scan_callback =
nullptr;
1475 if (_exit_game)
return;
1493 IncreaseSpriteLRU();
@ VEH_AIRCRAFT
Aircraft vehicle type.
static void Uninitialize(bool keepConfig)
Uninitialize the AI system.
@ WC_SAVELOAD
Saveload window; Window numbers:
int openttd_main(int argc, char *argv[])
Main entry point for this lovely game.
bool save_config
The save config setting.
static void Clear()
Clear all link graphs and jobs from the schedule.
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,...
static void ShutdownDrivers()
Shuts down all active drivers.
SwitchMode
Mode which defines what mode we're switching to.
void CheckEngines()
Check for engines that have an appropriate availability.
uint32 generation_seed
noise seed for world generation
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
class AIConfig * ai_config[MAX_COMPANIES]
settings per company
@ FT_SCENARIO
old or new scenario
static Titem * Get(size_t index)
Returns Titem with given index.
@ SAVE_DIR
Base directory for all savegames.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
@ SM_START_HEIGHTMAP
Load a heightmap and start a new game from it.
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
@ SM_LOAD_GAME
Load game, Play Scenario.
Dimensions (a width and height) of a rectangle in 2D.
void SetDParamStr(uint n, const char *str)
Set a rawstring parameter.
Company * DoStartupNewCompany(bool is_ai, CompanyID company=INVALID_COMPANY)
Create a new company and sets all company variables default values.
uint8 map_y
Y size of map.
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
std::string join_server_password
The password to join the server with.
struct LoggedAction * gamelog_action
Gamelog actions.
std::string _config_file
Configuration file of OpenTTD.
Class to backup a specific variable and restore it later.
uint16 server_port
port the server listens on
Vehicle * Next() const
Get the next vehicle of this vehicle.
Year _cur_year
Current year, starting at 0.
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?...
void CheckIndustries()
Verify whether the generated industries are complete, and warn the user if not.
bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=nullptr)
Load the specified savegame but on error do different things.
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
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.
virtual void SetVolume(byte vol)=0
Set the volume, if possible.
virtual void MainLoop()
Called once every tick.
DateFract _date_fract
Fractional part of the day.
@ SM_EDITOR
Switch to scenario editor.
std::string default_company_pass
default password for new companies in encrypted form
bool _network_server
network-server is active
std::string name
The name of the base set.
SaveLoadOperation
Operation performed on the file.
std::string name
Name of the file.
void UpdateNewGRFConfigPalette(int32 new_value)
Update the palettes of the graphics from the config file.
void SaveToConfig()
Save the values to the configuration file.
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
void InitWindowSystem()
(re)initialize the windowing system
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Tindex index
Index of this pool item.
static std::string GetConsoleList(bool newest_only=false)
Wrapper function for GameScanner::GetConsoleList.
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done.
int _skip_all_newgrf_scanning
Set this flag to prevent any NewGRF scanning from being done.
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
static Blitter * SelectBlitter(const std::string &name)
Find the requested blitter and return its class.
@ SLO_CHECK
Load file for checking and/or preview.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
bool _do_autosave
are we doing an autosave at the moment?
VehicleDefaultSettings vehicle
default settings for vehicles
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...
void UnInitWindowSystem()
Close down the windowing system.
@ DFT_GAME_FILE
Save game or scenario file.
class GameConfig * game_config
settings for gamescript
GRFConfig * grfconfig
NewGrf configuration from save.
CargoList that is used for stations.
void SetName(const char *name)
Set the name of the file.
static bool IsStandardRoadStopTile(TileIndex t)
Is tile t a standard (non-drive through) road stop station?
static const Year INVALID_YEAR
Representation of an invalid year.
bool HandleBootstrap()
Handle all procedures for bootstrapping OpenTTD without a base graphics set.
int32 Year
Type for the year, note: 0 based, i.e. starts at the year 0.
bool RequestNewGRFScan(NewGRFScanCallback *callback)
Request a new NewGRF scan.
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
ClientSettings _settings_client
The current settings for this game.
StringList _network_bind_list
The addresses to bind on.
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
void LoadFromHighScore()
Initialize the highscore table to 0 and if any file exists, load in values.
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
bool HasErrors()
Check whether loading the game resulted in errors.
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
byte _display_opt
What do we want to draw/do?
void SetDebugString(const char *s, void(*error_func)(const char *))
Set debugging levels by parsing the text in s.
SaveOrLoadResult LoadWithFilter(LoadFilter *reader)
Load the game using a (reader) filter.
#define GETOPT_SHORT_NOVAL(shortname)
Short option without value.
@ VEH_ROAD
Road vehicle type.
Defines the internal data of a functional industry.
AfterNewGRFScan()
Create a new callback.
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
@ SM_LOAD_SCENARIO
Load scenario from scenario editor.
Owner owner
Which company owns the vehicle?
Owner
Enum for all companies/owners.
static bool IsLocalCompany()
Is the current company the local company?
static void CheckCaches()
Check the validity of some of the caches.
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
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...
@ PFE_GL_LANDSCAPE
Time spent processing other world features.
@ GCF_COMPATIBLE
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches)
std::string _ini_musicdriver
The music driver a stored in the configuration file.
void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel wl, int x=0, int y=0, const GRFFile *textref_stack_grffile=nullptr, uint textref_stack_size=0, const uint32 *textref_stack=nullptr)
Display an error message in a window.
GameCreationSettings game_creation
settings used during the creation of a game (map)
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
@ PFE_GL_TRAINS
Time spent processing trains.
void UninitFontCache()
Free everything allocated w.r.t.
std::string NetworkChangeCompanyPassword(CompanyID company_id, std::string password)
Change the company password of a given company.
CargoList that is used for vehicles.
void RebuildTownCaches()
Rebuild all the cached variables of towns.
#define GETOPT_SHORT_OPTVAL(shortname)
Short option with optional value.
@ PM_UNPAUSED
A normal unpaused game.
void UpdateCache()
Update the caches of this ship.
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
@ COMPANY_FIRST
First company, same as owner.
@ DO_FULL_ANIMATION
Perform palette animation.
void NetworkClientJoinGame()
Actually perform the joining to the server.
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Colours _company_colours[MAX_COMPANIES]
NOSAVE: can be determined from company structs.
static void OnStartGame(bool dedicated_server)
Triggers everything that should be triggered when starting a game.
@ COMPANY_NEW_COMPANY
The client wants a new company.
@ SLO_LOAD
File is being loaded.
Cached, frequently calculated values.
char * DumpDebugFacilityNames(char *buf, char *last)
Dump the available debug facility names in the help text.
uint32 generation_seed
Seed for the new game.
byte colour
Company colour.
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
Date _date
Current date in days (day counter)
std::string last_joined
Last joined server.
@ SLO_SAVE
File is being saved.
Information about GRF, used in the game and (part of it) in savegames.
@ PM_PAUSED_SAVELOAD
A game paused for saving/loading.
static MusicDriver * GetInstance()
Get the currently active instance of the music driver.
@ SM_NEWGAME
New Game --> 'Random game'.
static char * GetDriversInfo(char *p, const char *last)
Build a human readable list of available drivers, grouped by type.
byte starting_colour
default color scheme for the company to start a new game with
@ S8BPP_NONE
No support for 8bpp by OS or hardware, force 32bpp blitters.
Year startyear
The start year.
@ SM_SAVE_HEIGHTMAP
Save heightmap.
char * error_data
Data to pass to SetDParamStr when displaying error.
uint gamelog_actions
Number of gamelog actions.
const char * GetSaveLoadErrorString()
Get the string representation of the error message.
@ VS_CRASHED
Vehicle is crashed.
@ GWM_RANDOM
Generate a random map for SE.
static void SetErrorMessage(const char *message)
Sets a message for the error message handler.
uint16 w
The width of the area.
static void ShowHelp()
Show the help message when someone passed a wrong parameter.
@ PFE_GL_SHIPS
Time spent processing ships.
#define GETOPT_END()
Option terminator.
void InitFontCache(bool monospace)
(Re)initialize the font cache related things, i.e.
static void ParseResolution(Dimension *res, const char *s)
Extract the resolution from the given string and store it in the 'res' parameter.
bool pause_on_newgame
whether to start new games paused or not
static AIConfig * GetConfig(CompanyID company, ScriptSettingSource source=SSS_DEFAULT)
Get the config of a company.
void AfterLoadCompanyStats()
Rebuilding of company statistics after loading a savegame.
@ SL_REINIT
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
static void OnStartScenario()
Triggers everything required to set up a saved scenario for a new game.
GroundVehicleCache gcache
Cache of often calculated values.
Represents the covered area of e.g.
PauseMode _pause_mode
The current pause mode.
static void Initialize()
Initialize the AI system.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
CompanySettings settings
settings specific for each company
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
static void ShutdownGame()
Uninitializes drivers, frees allocated memory, cleans pools, ...
static void DoAutosave()
Create an autosave.
Cached often queried values common to all vehicles.
@ MAX_COMPANIES
Maximum number of companies.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
void NetworkDisconnect(bool blocking, bool close_admins)
We want to disconnect from the host/clients.
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
static void Clean(PoolType)
Clean all pools of given type.
@ FT_INVALID
Invalid or unknown file type.
void NetworkShutDown()
This shuts the network down.
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
static void Uninitialize(bool keepConfig)
Uninitialize the Game system.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
std::string_view ParseFullConnectionString(const std::string &connection_string, uint16 &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
bool _networking
are we in networking mode?
char * opt
Option value, if available (else nullptr).
void ScanNewGRFFiles(NewGRFScanCallback *callback)
Scan for all NewGRFs.
The data of the error message.
@ DFT_OLD_GAME_FILE
Old save game or scenario file.
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
uint8 _network_reconnect
Reconnect timeout.
bool _network_dedicated
are we a dedicated server?
static void GameLoop()
Called every game-tick to let AIs do something.
static void SaveToConfig()
Save all WindowDesc settings to _windows_file.
@ FT_SAVEGAME
old or new savegame
GameMode
Mode which defines the state of the game.
@ SM_GENRANDLAND
Generate random land within scenario editor.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Data storage for parsing command line options.
StringID error
Error message from loading. INVALID_STRING_ID if no error.
static void ReduceLineCache()
Reduce the size of linecache if necessary to prevent infinite growth.
std::string join_company_password
The password to join the company with.
uint16 h
The height of the area.
StringID name
The name for this object.
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
@ SM_LOAD_HEIGHTMAP
Load heightmap from scenario editor.
void IncreaseDate()
Increases the tick counter, increases date and possibly calls procedures that have to be called daily...
bool _blitter_autodetected
Was the blitter autodetected or specified by the user?
@ DFT_INVALID
Unknown or invalid file.
SwitchMode _switch_mode
The next mainloop command.
CompanyID _current_company
Company currently doing an action.
static void GameLoop()
Called every game-tick to let Game do something.
@ DT_SOUND
A sound driver.
@ SCENARIO
Scan for scenarios and heightmaps.
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
@ PFE_GAMELOOP
Speed of gameloop processing.
A savegame name automatically numbered.
static void KillAll()
Kill any and all AIs we manage.
DetailedFileType
Kinds of files in each AbstractFileType.
void Clear()
Reset read data.
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
@ PFE_GL_ECONOMY
Time spent processing cargo movement.
void SaveToHighScore()
Save HighScore table to file.
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
void FillNewGRFVehicleCache(const Vehicle *v)
Fill the grf_cache of the given vehicle.
void Restore()
Restore the variable.
uint16 dedicated_port
Port for the dedicated server.
std::string _ini_blitter
The blitter as stored in the configuration file.
FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const std::string &file, const char *ext, char *title, const char *last)
Callback for FiosGetFileList.
uint8 map_x
X size of map.
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
@ NO_DIRECTORY
A path without any base directory.
@ COMPANY_SPECTATOR
The client is spectating.
TileIndex tile
The base tile of the area.
@ DT_VIDEO
A video driver.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
struct GRFConfig * next
NOSAVE: Next item in the linked list.
std::string _ini_sounddriver
The sound driver a stored in the configuration file.
void ScheduleErrorMessage(const ErrorMessageData &data)
Schedule an error.
@ OWNER_NONE
The tile has no ownership.
@ PM_PAUSED_NORMAL
A game normally paused.
static const OptionData _options[]
Options of OpenTTD.
@ GWM_EMPTY
Generate an empty map (sea-level)
@ SM_RESTART_HEIGHTMAP
Load a heightmap and start a new game from it with current settings.
@ NUM_CARGO
Maximal number of cargo types in a game.
@ PFE_ALLSCRIPTS
Sum of all GS/AI scripts.
bool disable_elrails
when true, the elrails are disabled
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
void CDECL ShowInfoF(const char *str,...)
Shows some information on the console/a popup box depending on the OS.
void DebugSendRemoteMessages()
Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the GameLoop threa...
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
@ FT_HEIGHTMAP
heightmap file
Subdirectory
The different kinds of subdirectories OpenTTD uses.
void ResetNewGRFData()
Reset all NewGRF loaded data.
Year starting_year
starting date
UnitID unitnumber
unit number, for display purposes only
SaveOrLoadResult
Save or load result codes.
@ WL_ERROR
Errors (eg. saving/loading failed)
void GamelogReset()
Resets and frees all memory allocated - used before loading or starting a new game.
@ SM_RELOADGAME
Reload the savegame / scenario / heightmap you started the game with.
FiosType
Elements of a file system that are recognized.
@ SM_MENU
Switch to game intro menu.
void AnimateAnimatedTiles()
Animate all tiles in the animated tile list, i.e. call AnimateTile on them.
@ GWM_NEWGAME
Generate a map for a new game.
int GetOpt()
Find the next option.
static void SelectDriver(const std::string &name, Driver::Type type)
Find the requested driver and return its class.
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Callback structure of statements to be executed after the NewGRF scan.
void MusicLoop()
Check music playback status and start/stop/song-finished.
static bool IsDockingTile(TileIndex t)
Checks whether the tile is marked as a dockling tile.
bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password, const std::string &join_company_password)
Join a client to the server at with the given connection string.
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
@ SLO_INVALID
Unknown file operation.
static std::string GetConsoleList(bool newest_only=false)
Wrapper function for AIScanner::GetAIConsoleList.
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Callback for NewGRF scanning.
Interface for filtering a savegame till it is loaded.
Variables that are cached to improve performance and such.
byte effect_vol
The requested effects volume.
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
NetworkSettings network
settings related to the network
void LoadHotkeysFromConfig()
Load the hotkeys from the config file.
virtual void MainLoop()=0
Perform the actual drawing.
byte CargoID
Cargo slots to indicate a cargo type within a game.
void CloseWindowById(WindowClass cls, WindowNumber number, bool force)
Close a window by its class and window number (if it is open).
@ BASESET
Scan for base sets.
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
static SoundDriver * GetInstance()
Get the currently active instance of the sound driver.
@ PSM_LEAVE_GAMELOOP
Leave the gameloop, changes will be temporary.
@ INVALID_COMPANY
An invalid company.
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...
void IConsoleCmdExec(const char *cmdstr, const uint recurse_count)
Execute a given command passed to us.
void Change(const char *name, int version=-1, bool force_exact_match=false, bool is_random=false)
Set another Script to be loaded in this slot.
void ProcessAsyncSaveFinish()
Handle async save finishes.
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
static void LoadIntroGame(bool load_newgrfs=true)
Load the introduction game.
@ ZOOM_LVL_NORMAL
The normal zoom level.
std::string connection_string
Information about the server to connect to.
CompanySettings company
default values for per-company settings
uint32 last_newgrf_count
the numbers of NewGRFs we found during the last scan
@ CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
VehicleSettings vehicle
options for vehicles
bool HasNewGrfs()
Check whether the game uses any NewGrfs.
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
@ VEH_TRAIN
Train vehicle type.
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
void ResetGRFConfig(bool defaults)
Reset the current GRF Config to either blank or newgame settings.
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
A Stop for a Road Vehicle.
VehicleType type
Type of vehicle.
void StateGameLoop()
State controlling game loop.
void NetworkStartUp()
This tries to launch the network for a given OS.
static bool HasModalProgress()
Check if we are currently in a modal progress state.
void InitializeSpriteSorter()
Choose the "best" sprite sorter and set _vp_sprite_sorter.
@ DT_MUSIC
A music driver, needs to be before sound to properly shut down extmidi forked music players.
std::string dedicated_host
Hostname for the dedicated server.
bool _network_available
is network mode available?
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
void InitializeRoadGUI()
I really don't know why rail_gui.cpp has this too, shouldn't be included in the other one?
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
static int MemCmpT(const T *ptr1, const T *ptr2, size_t num=1)
Type-safe version of memcmp().
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...
bool reload_cfg
reload the config file before restarting
@ DIAGDIR_NE
Northeast, upper right on your monitor.
@ VEH_SHIP
Ship vehicle type.
#define GETOPT_SHORT_VALUE(shortname)
Short option with value.
@ SM_JOIN_GAME
Join a network game.
virtual void Stop()=0
Stop this driver.
@ SSS_FORCE_GAME
Get the Script config from the current game.
bool in_window
mouse inside this window, determines drawing logic
MusicSettings music
settings related to music/sound
#define lastof(x)
Get the last element of an fixed size array.
@ SL_OK
completed successfully
void NetworkServerUpdateGameInfo()
Update the server's NetworkServerGameInfo due to changes in settings.
void LoadFromConfig(bool startup)
Load the values from the configuration files.
byte music_vol
The requested music volume.
SaveLoadVersion _sl_version
the major savegame version identifier
void UpdateLandscapingLimits()
Update the landscaping limits per company.
Dimension _cur_resolution
The current resolution.
bool _is_network_server
Does this client wants to be a network-server?
int numleft
Number of arguments left in argv.
void GamelogInfo(LoggedAction *gamelog_action, uint gamelog_actions, uint32 *last_ottd_rev, byte *ever_modified, bool *removed_newgrfs)
Get some basic information from the given gamelog.
std::string _ini_videodriver
The video driver a stored in the configuration file.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
static char * GetBlittersInfo(char *p, const char *last)
Fill a buffer with information about the blitters.
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
GUISettings gui
settings related to the GUI
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
void InitializeLanguagePacks()
Make a list of the available language packs.
Cached often queried (NewGRF) values.
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
void SettingsDisableElrail(int32 new_value)
_settings_game.disable_elrail callback
SaveLoadOperation file_op
File operation to perform.
void StateGameLoop_LinkGraphPauseControl()
Pause the game if in 2 _date_fract ticks, we would do a join with the next link graph job,...
virtual void OnNewGRFsScanned()
Called whenever the NewGRF scan completed.
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every 256 ticks.
@ SM_RESTARTGAME
Restart --> 'Random game' with current settings.
static void Initialize()
Initialize the Game system.