OpenTTD Source  1.10.2
openttd.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 
12 #include "blitter/factory.hpp"
13 #include "sound/sound_driver.hpp"
14 #include "music/music_driver.hpp"
15 #include "video/video_driver.hpp"
16 
17 #include "fontcache.h"
18 #include "error.h"
19 #include "gui.h"
20 
21 #include "base_media_base.h"
22 #include "saveload/saveload.h"
23 #include "company_func.h"
24 #include "command_func.h"
25 #include "news_func.h"
26 #include "fios.h"
27 #include "aircraft.h"
28 #include "roadveh.h"
29 #include "train.h"
30 #include "ship.h"
31 #include "console_func.h"
32 #include "screenshot.h"
33 #include "network/network.h"
34 #include "network/network_func.h"
35 #include "ai/ai.hpp"
36 #include "ai/ai_config.hpp"
37 #include "settings_func.h"
38 #include "genworld.h"
39 #include "progress.h"
40 #include "strings_func.h"
41 #include "date_func.h"
42 #include "vehicle_func.h"
43 #include "gamelog.h"
44 #include "animated_tile_func.h"
45 #include "roadstop_base.h"
46 #include "elrail_func.h"
47 #include "rev.h"
48 #include "highscore.h"
49 #include "station_base.h"
50 #include "crashlog.h"
51 #include "engine_func.h"
52 #include "core/random_func.hpp"
53 #include "rail_gui.h"
54 #include "road_gui.h"
55 #include "core/backup_type.hpp"
56 #include "hotkeys.h"
57 #include "newgrf.h"
58 #include "misc/getoptdata.h"
59 #include "game/game.hpp"
60 #include "game/game_config.hpp"
61 #include "town.h"
62 #include "subsidy_func.h"
63 #include "gfx_layout.h"
64 #include "viewport_func.h"
65 #include "viewport_sprite_sorter.h"
66 #include "framerate_type.h"
67 #include "industry.h"
68 
70 
71 #include <stdarg.h>
72 #include <system_error>
73 
74 #include "safeguards.h"
75 
76 void CallLandscapeTick();
77 void IncreaseDate();
78 void DoPaletteAnimations();
79 void MusicLoop();
80 void ResetMusic();
82 bool HandleBootstrap();
83 
84 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
85 extern void ShowOSErrorBox(const char *buf, bool system);
86 extern char *_config_file;
87 
93 void CDECL usererror(const char *s, ...)
94 {
95  va_list va;
96  char buf[512];
97 
98  va_start(va, s);
99  vseprintf(buf, lastof(buf), s, va);
100  va_end(va);
101 
102  ShowOSErrorBox(buf, false);
104 
105  exit(1);
106 }
107 
113 void CDECL error(const char *s, ...)
114 {
115  va_list va;
116  char buf[512];
117 
118  va_start(va, s);
119  vseprintf(buf, lastof(buf), s, va);
120  va_end(va);
121 
122  if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
123  ShowOSErrorBox(buf, true);
124  }
125 
126  /* Set the error message for the crash log and then invoke it. */
128  abort();
129 }
130 
135 void CDECL ShowInfoF(const char *str, ...)
136 {
137  va_list va;
138  char buf[1024];
139  va_start(va, str);
140  vseprintf(buf, lastof(buf), str, va);
141  va_end(va);
142  ShowInfo(buf);
143 }
144 
148 static void ShowHelp()
149 {
150  char buf[8192];
151  char *p = buf;
152 
153  p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
154  p = strecpy(p,
155  "\n"
156  "\n"
157  "Command line options:\n"
158  " -v drv = Set video driver (see below)\n"
159  " -s drv = Set sound driver (see below) (param bufsize,hz)\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] = Start new/save game immediately\n"
168  " -G seed = Set random seed\n"
169  " -n [ip:port#company]= Join network game\n"
170  " -p password = Password to join server\n"
171  " -P password = Password to join company\n"
172  " -D [ip][:port] = Start dedicated server\n"
173  " -l ip[:port] = Redirect DEBUG()\n"
174 #if !defined(_WIN32)
175  " -f = Fork into the background (dedicated only)\n"
176 #endif
177  " -I graphics_set = Force the graphics set (see below)\n"
178  " -S sounds_set = Force the sounds set (see below)\n"
179  " -M music_set = Force the music set (see below)\n"
180  " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
181  " -x = Do not automatically save to config file on exit\n"
182  " -q savegame = Write some information about the savegame and exit\n"
183  "\n",
184  lastof(buf)
185  );
186 
187  /* List the graphics packs */
188  p = BaseGraphics::GetSetsList(p, lastof(buf));
189 
190  /* List the sounds packs */
191  p = BaseSounds::GetSetsList(p, lastof(buf));
192 
193  /* List the music packs */
194  p = BaseMusic::GetSetsList(p, lastof(buf));
195 
196  /* List the drivers */
198 
199  /* List the blitters */
201 
202  /* List the debug facilities. */
203  p = DumpDebugFacilityNames(p, lastof(buf));
204 
205  /* We need to initialize the AI, so it finds the AIs */
206  AI::Initialize();
207  p = AI::GetConsoleList(p, lastof(buf), true);
208  AI::Uninitialize(true);
209 
210  /* We need to initialize the GameScript, so it finds the GSs */
212  p = Game::GetConsoleList(p, lastof(buf), true);
213  Game::Uninitialize(true);
214 
215  /* ShowInfo put output to stderr, but version information should go
216  * to stdout; this is the only exception */
217 #if !defined(_WIN32)
218  printf("%s\n", buf);
219 #else
220  ShowInfo(buf);
221 #endif
222 }
223 
224 static void WriteSavegameInfo(const char *name)
225 {
227  uint32 last_ottd_rev = 0;
228  byte ever_modified = 0;
229  bool removed_newgrfs = false;
230 
231  GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
232 
233  char buf[8192];
234  char *p = buf;
235  p += seprintf(p, lastof(buf), "Name: %s\n", name);
236  p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
237  p += seprintf(p, lastof(buf), "NewGRF ver: 0x%08X\n", last_ottd_rev);
238  p += seprintf(p, lastof(buf), "Modified: %d\n", ever_modified);
239 
240  if (removed_newgrfs) {
241  p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
242  }
243 
244  p = strecpy(p, "NewGRFs:\n", lastof(buf));
246  for (GRFConfig *c = _load_check_data.grfconfig; c != nullptr; c = c->next) {
247  char md5sum[33];
248  md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
249  p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
250  }
251  }
252 
253  /* ShowInfo put output to stderr, but version information should go
254  * to stdout; this is the only exception */
255 #if !defined(_WIN32)
256  printf("%s\n", buf);
257 #else
258  ShowInfo(buf);
259 #endif
260 }
261 
262 
269 static void ParseResolution(Dimension *res, const char *s)
270 {
271  const char *t = strchr(s, 'x');
272  if (t == nullptr) {
273  ShowInfoF("Invalid resolution '%s'", s);
274  return;
275  }
276 
277  res->width = max(strtoul(s, nullptr, 0), 64UL);
278  res->height = max(strtoul(t + 1, nullptr, 0), 64UL);
279 }
280 
281 
286 static void ShutdownGame()
287 {
288  IConsoleFree();
289 
290  if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
291 
293 
295 
296  /* stop the scripts */
297  AI::Uninitialize(false);
298  Game::Uninitialize(false);
299 
300  /* Uninitialize variables that are allocated dynamically */
301  GamelogReset();
302 
304 
307 
308  /* No NewGRFs were loaded when it was still bootstrapping. */
309  if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
310 
311  /* Close all and any open filehandles */
312  FioCloseAll();
313 
314  UninitFreeType();
315 }
316 
321 static void LoadIntroGame(bool load_newgrfs = true)
322 {
323  _game_mode = GM_MENU;
324 
325  if (load_newgrfs) ResetGRFConfig(false);
326 
327  /* Setup main window */
330 
331  /* Load the default opening screen savegame */
332  if (SaveOrLoad("opntitle.dat", SLO_LOAD, DFT_GAME_FILE, BASESET_DIR) != SL_OK) {
333  GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
336  } else {
338  }
339 
340  FixTitleGameZoom();
342  _cursor.fix_at = false;
343 
345 
346  MusicLoop(); // ensure music is correct
347 }
348 
349 void MakeNewgameSettingsLive()
350 {
351  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
352  if (_settings_game.ai_config[c] != nullptr) {
353  delete _settings_game.ai_config[c];
354  }
355  }
356  if (_settings_game.game_config != nullptr) {
358  }
359 
360  /* Copy newgame settings to active settings.
361  * Also initialise old settings needed for savegame conversion. */
364 
365  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
366  _settings_game.ai_config[c] = nullptr;
367  if (_settings_newgame.ai_config[c] != nullptr) {
369  if (!AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->HasScript()) {
371  }
372  }
373  }
374  _settings_game.game_config = nullptr;
375  if (_settings_newgame.game_config != nullptr) {
377  }
378 }
379 
380 void OpenBrowser(const char *url)
381 {
382  /* Make sure we only accept urls that are sure to open a browser. */
383  if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
384 
385  extern void OSOpenBrowser(const char *url);
386  OSOpenBrowser(url);
387 }
388 
394  uint16 dedicated_port;
395  char *network_conn;
396  const char *join_server_password;
397  const char *join_company_password;
399  bool save_config;
400 
406  AfterNewGRFScan(bool *save_config_ptr) :
407  startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
408  dedicated_host(nullptr), dedicated_port(0), network_conn(nullptr),
409  join_server_password(nullptr), join_company_password(nullptr),
410  save_config_ptr(save_config_ptr), save_config(true)
411  {
412  /* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
413  * if it's placed outside a member function, directly in the struct body. */
414  assert_compile(sizeof(generation_seed) == sizeof(_settings_game.game_creation.generation_seed));
415  }
416 
417  virtual void OnNewGRFsScanned()
418  {
419  ResetGRFConfig(false);
420 
422 
423  AI::Initialize();
425 
426  /* We want the new (correct) NewGRF count to survive the loading. */
427  uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
428  LoadFromConfig();
429  _settings_client.gui.last_newgrf_count = last_newgrf_count;
430  /* Since the default for the palette might have changed due to
431  * reading the configuration file, recalculate that now. */
433 
434  Game::Uninitialize(true);
435  AI::Uninitialize(true);
439 
440  /* We have loaded the config, so we may possibly save it. */
441  *save_config_ptr = save_config;
442 
443  /* restore saved music volume */
445 
448 
449  if (dedicated_host != nullptr) {
450  _network_bind_list.clear();
451  _network_bind_list.emplace_back(dedicated_host);
452  }
453  if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
454 
455  /* initialize the ingame console */
456  IConsoleInit();
457  InitializeGUI();
458  IConsoleCmdExec("exec scripts/autoexec.scr 0");
459 
460  /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
461  if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
462 
463  if (_network_available && network_conn != nullptr) {
464  const char *port = nullptr;
465  const char *company = nullptr;
466  uint16 rport = NETWORK_DEFAULT_PORT;
467  CompanyID join_as = COMPANY_NEW_COMPANY;
468 
469  ParseConnectionString(&company, &port, network_conn);
470 
471  if (company != nullptr) {
472  join_as = (CompanyID)atoi(company);
473 
474  if (join_as != COMPANY_SPECTATOR) {
475  join_as--;
476  if (join_as >= MAX_COMPANIES) {
477  delete this;
478  return;
479  }
480  }
481  }
482  if (port != nullptr) rport = atoi(port);
483 
484  LoadIntroGame();
485  _switch_mode = SM_NONE;
486  NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
487  }
488 
489  /* After the scan we're not used anymore. */
490  delete this;
491  }
492 };
493 
494 #if defined(UNIX)
495 extern void DedicatedFork();
496 #endif
497 
499 static const OptionData _options[] = {
500  GETOPT_SHORT_VALUE('I'),
501  GETOPT_SHORT_VALUE('S'),
502  GETOPT_SHORT_VALUE('M'),
503  GETOPT_SHORT_VALUE('m'),
504  GETOPT_SHORT_VALUE('s'),
505  GETOPT_SHORT_VALUE('v'),
506  GETOPT_SHORT_VALUE('b'),
507  GETOPT_SHORT_OPTVAL('D'),
508  GETOPT_SHORT_OPTVAL('n'),
509  GETOPT_SHORT_VALUE('l'),
510  GETOPT_SHORT_VALUE('p'),
511  GETOPT_SHORT_VALUE('P'),
512 #if !defined(_WIN32)
513  GETOPT_SHORT_NOVAL('f'),
514 #endif
515  GETOPT_SHORT_VALUE('r'),
516  GETOPT_SHORT_VALUE('t'),
517  GETOPT_SHORT_OPTVAL('d'),
518  GETOPT_SHORT_NOVAL('e'),
519  GETOPT_SHORT_OPTVAL('g'),
520  GETOPT_SHORT_VALUE('G'),
521  GETOPT_SHORT_VALUE('c'),
522  GETOPT_SHORT_NOVAL('x'),
523  GETOPT_SHORT_VALUE('q'),
524  GETOPT_SHORT_NOVAL('h'),
525  GETOPT_END()
526 };
527 
534 int openttd_main(int argc, char *argv[])
535 {
536  char *musicdriver = nullptr;
537  char *sounddriver = nullptr;
538  char *videodriver = nullptr;
539  char *blitter = nullptr;
540  char *graphics_set = nullptr;
541  char *sounds_set = nullptr;
542  char *music_set = nullptr;
543  Dimension resolution = {0, 0};
544  /* AfterNewGRFScan sets save_config to true after scanning completed. */
545  bool save_config = false;
546  AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
547  bool dedicated = false;
548  char *debuglog_conn = nullptr;
549 
550  extern bool _dedicated_forks;
551  _dedicated_forks = false;
552 
553  std::unique_lock<std::mutex> modal_work_lock(_modal_progress_work_mutex, std::defer_lock);
554  std::unique_lock<std::mutex> modal_paint_lock(_modal_progress_paint_mutex, std::defer_lock);
555 
556  _game_mode = GM_MENU;
558  _config_file = nullptr;
559 
560  GetOptData mgo(argc - 1, argv + 1, _options);
561  int ret = 0;
562 
563  int i;
564  while ((i = mgo.GetOpt()) != -1) {
565  switch (i) {
566  case 'I': free(graphics_set); graphics_set = stredup(mgo.opt); break;
567  case 'S': free(sounds_set); sounds_set = stredup(mgo.opt); break;
568  case 'M': free(music_set); music_set = stredup(mgo.opt); break;
569  case 'm': free(musicdriver); musicdriver = stredup(mgo.opt); break;
570  case 's': free(sounddriver); sounddriver = stredup(mgo.opt); break;
571  case 'v': free(videodriver); videodriver = stredup(mgo.opt); break;
572  case 'b': free(blitter); blitter = stredup(mgo.opt); break;
573  case 'D':
574  free(musicdriver);
575  free(sounddriver);
576  free(videodriver);
577  free(blitter);
578  musicdriver = stredup("null");
579  sounddriver = stredup("null");
580  videodriver = stredup("dedicated");
581  blitter = stredup("null");
582  dedicated = true;
583  SetDebugString("net=6");
584  if (mgo.opt != nullptr) {
585  /* Use the existing method for parsing (openttd -n).
586  * However, we do ignore the #company part. */
587  const char *temp = nullptr;
588  const char *port = nullptr;
589  ParseConnectionString(&temp, &port, mgo.opt);
590  if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
591  if (port != nullptr) scanner->dedicated_port = atoi(port);
592  }
593  break;
594  case 'f': _dedicated_forks = true; break;
595  case 'n':
596  scanner->network_conn = mgo.opt; // optional IP parameter, nullptr if unset
597  break;
598  case 'l':
599  debuglog_conn = mgo.opt;
600  break;
601  case 'p':
602  scanner->join_server_password = mgo.opt;
603  break;
604  case 'P':
605  scanner->join_company_password = mgo.opt;
606  break;
607  case 'r': ParseResolution(&resolution, mgo.opt); break;
608  case 't': scanner->startyear = atoi(mgo.opt); break;
609  case 'd': {
610 #if defined(_WIN32)
611  CreateConsole();
612 #endif
613  if (mgo.opt != nullptr) SetDebugString(mgo.opt);
614  break;
615  }
617  case 'g':
618  if (mgo.opt != nullptr) {
620  bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
621  _switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
623 
624  /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
625  const char *t = strrchr(_file_to_saveload.name, '.');
626  if (t != nullptr) {
628  if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
629  }
630 
631  break;
632  }
633 
635  /* Give a random map if no seed has been given */
636  if (scanner->generation_seed == GENERATE_NEW_SEED) {
637  scanner->generation_seed = InteractiveRandom();
638  }
639  break;
640  case 'q': {
641  DeterminePaths(argv[0]);
642  if (StrEmpty(mgo.opt)) {
643  ret = 1;
644  goto exit_noshutdown;
645  }
646 
647  char title[80];
648  title[0] = '\0';
649  FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
650 
653  if (res != SL_OK || _load_check_data.HasErrors()) {
654  fprintf(stderr, "Failed to open savegame\n");
655  if (_load_check_data.HasErrors()) {
656  char buf[256];
658  GetString(buf, _load_check_data.error, lastof(buf));
659  fprintf(stderr, "%s\n", buf);
660  }
661  goto exit_noshutdown;
662  }
663 
664  WriteSavegameInfo(title);
665 
666  goto exit_noshutdown;
667  }
668  case 'G': scanner->generation_seed = strtoul(mgo.opt, nullptr, 10); break;
669  case 'c': free(_config_file); _config_file = stredup(mgo.opt); break;
670  case 'x': scanner->save_config = false; break;
671  case 'h':
672  i = -2; // Force printing of help.
673  break;
674  }
675  if (i == -2) break;
676  }
677 
678  if (i == -2 || mgo.numleft > 0) {
679  /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
680  * In all cases, print the help, and exit.
681  *
682  * The next two functions are needed to list the graphics sets. We can't do them earlier
683  * because then we cannot show it on the debug console as that hasn't been configured yet. */
684  DeterminePaths(argv[0]);
689  ShowHelp();
690 
691  goto exit_noshutdown;
692  }
693 
694  DeterminePaths(argv[0]);
696 
697  if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
698  if (_dedicated_forks && !dedicated) _dedicated_forks = false;
699 
700 #if defined(UNIX)
701  /* We must fork here, or we'll end up without some resources we need (like sockets) */
702  if (_dedicated_forks) DedicatedFork();
703 #endif
704 
705  LoadFromConfig(true);
706 
707  if (resolution.width != 0) _cur_resolution = resolution;
708 
709  /*
710  * The width and height must be at least 1 pixel and width times
711  * height times bytes per pixel must still fit within a 32 bits
712  * integer, even for 32 bpp video modes. This way all internal
713  * drawing routines work correctly.
714  */
715  _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX / 2);
716  _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
717 
718  /* Assume the cursor starts within the game as not all video drivers
719  * get an event that the cursor is within the window when it is opened.
720  * Saying the cursor is there makes no visible difference as it would
721  * just be out of the bounds of the window. */
722  _cursor.in_window = true;
723 
724  /* enumerate language files */
726 
727  /* Initialize the regular font for FreeType */
728  InitFreeType(false);
729 
730  /* This must be done early, since functions use the SetWindowDirty* calls */
732 
734  if (graphics_set == nullptr && BaseGraphics::ini_set != nullptr) graphics_set = stredup(BaseGraphics::ini_set);
735  if (!BaseGraphics::SetSet(graphics_set)) {
736  if (!StrEmpty(graphics_set)) {
737  BaseGraphics::SetSet(nullptr);
738 
739  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
740  msg.SetDParamStr(0, graphics_set);
742  }
743  }
744  free(graphics_set);
745 
746  /* Initialize game palette */
747  GfxInitPalettes();
748 
749  DEBUG(misc, 1, "Loading blitter...");
750  if (blitter == nullptr && _ini_blitter != nullptr) blitter = stredup(_ini_blitter);
751  _blitter_autodetected = StrEmpty(blitter);
752  /* Activate the initial blitter.
753  * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
754  * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
755  * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
756  * - Use 8bpp blitter otherwise.
757  */
758  if (!_blitter_autodetected ||
759  (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
760  BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
761  if (BlitterFactory::SelectBlitter(blitter) == nullptr) {
762  StrEmpty(blitter) ?
763  usererror("Failed to autoprobe blitter") :
764  usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
765  }
766  }
767  free(blitter);
768 
769  if (videodriver == nullptr && _ini_videodriver != nullptr) videodriver = stredup(_ini_videodriver);
771  free(videodriver);
772 
774 
775  /* Initialize the zoom level of the screen to normal */
776  _screen.zoom = ZOOM_LVL_NORMAL;
777 
778  NetworkStartUp(); // initialize network-core
779 
780  if (debuglog_conn != nullptr && _network_available) {
781  const char *not_used = nullptr;
782  const char *port = nullptr;
783  uint16 rport;
784 
786 
787  ParseConnectionString(&not_used, &port, debuglog_conn);
788  if (port != nullptr) rport = atoi(port);
789 
790  NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
791  }
792 
793  if (!HandleBootstrap()) {
794  ShutdownGame();
795 
796  goto exit_bootstrap;
797  }
798 
799  VideoDriver::GetInstance()->ClaimMousePointer();
800 
801  /* initialize screenshot formats */
803 
805  if (sounds_set == nullptr && BaseSounds::ini_set != nullptr) sounds_set = stredup(BaseSounds::ini_set);
806  if (!BaseSounds::SetSet(sounds_set)) {
807  if (StrEmpty(sounds_set) || !BaseSounds::SetSet(nullptr)) {
808  usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
809  } else {
810  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
811  msg.SetDParamStr(0, sounds_set);
813  }
814  }
815  free(sounds_set);
816 
818  if (music_set == nullptr && BaseMusic::ini_set != nullptr) music_set = stredup(BaseMusic::ini_set);
819  if (!BaseMusic::SetSet(music_set)) {
820  if (StrEmpty(music_set) || !BaseMusic::SetSet(nullptr)) {
821  usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
822  } else {
823  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
824  msg.SetDParamStr(0, music_set);
826  }
827  }
828  free(music_set);
829 
830  if (sounddriver == nullptr && _ini_sounddriver != nullptr) sounddriver = stredup(_ini_sounddriver);
832  free(sounddriver);
833 
834  if (musicdriver == nullptr && _ini_musicdriver != nullptr) musicdriver = stredup(_ini_musicdriver);
836  free(musicdriver);
837 
838  /* Take our initial lock on whatever we might want to do! */
839  try {
840  modal_work_lock.lock();
841  modal_paint_lock.lock();
842  } catch (const std::system_error&) {
843  /* If there is some error we assume that threads aren't usable on the system we run. */
844  extern bool _use_threaded_modal_progress; // From progress.cpp
845  _use_threaded_modal_progress = false;
846  }
847 
848  GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
850 
851  LoadIntroGame(false);
852 
854 
855  /* ScanNewGRFFiles now has control over the scanner. */
856  ScanNewGRFFiles(scanner);
857  scanner = nullptr;
858 
860 
861  WaitTillSaved();
862  WaitTillGeneratedWorld(); // Make sure any generate world threads have been joined.
863 
864  /* only save config if we have to */
865  if (save_config) {
866  SaveToConfig();
869  SaveToHighScore();
870  }
871 
872  /* Reset windowing system, stop drivers, free used memory, ... */
873  ShutdownGame();
874  goto exit_normal;
875 
876 exit_noshutdown:
877  /* These three are normally freed before bootstrap. */
878  free(graphics_set);
879  free(videodriver);
880  free(blitter);
881 
882 exit_bootstrap:
883  /* These are normally freed before exit, but after bootstrap. */
884  free(sounds_set);
885  free(music_set);
886  free(musicdriver);
887  free(sounddriver);
888 
889 exit_normal:
893 
898 
899  delete scanner;
900 
901  extern FILE *_log_fd;
902  if (_log_fd != nullptr) {
903  fclose(_log_fd);
904  }
905 
906  return ret;
907 }
908 
909 void HandleExitGameRequest()
910 {
911  if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
912  _exit_game = true;
914  DoExitSave();
915  _exit_game = true;
916  } else {
917  AskExitGame();
918  }
919 }
920 
921 static void MakeNewGameDone()
922 {
924 
925  /* In a dedicated server, the server does not play */
926  if (!VideoDriver::GetInstance()->HasGUI()) {
929  IConsoleCmdExec("exec scripts/game_start.scr 0");
930  return;
931  }
932 
933  /* Create a single company */
934  DoStartupNewCompany(false);
935 
938 
939  /* Overwrite color from settings if needed
940  * COLOUR_END corresponds to Random colour */
941  if (_settings_client.gui.starting_colour != COLOUR_END) {
944  _company_colours[c->index] = (Colours)c->colour;
945  }
946 
947  IConsoleCmdExec("exec scripts/game_start.scr 0");
948 
950 
953 
954  /* We are the server, we start a new company (not dedicated),
955  * so set the default password *if* needed. */
958  }
959 
961 
962  CheckEngines();
963  CheckIndustries();
965 }
966 
967 static void MakeNewGame(bool from_heightmap, bool reset_settings)
968 {
969  _game_mode = GM_NORMAL;
970 
971  ResetGRFConfig(true);
972 
973  GenerateWorldSetCallback(&MakeNewGameDone);
975 }
976 
977 static void MakeNewEditorWorldDone()
978 {
980 }
981 
982 static void MakeNewEditorWorld()
983 {
984  _game_mode = GM_EDITOR;
985 
986  ResetGRFConfig(true);
987 
988  GenerateWorldSetCallback(&MakeNewEditorWorldDone);
990 }
991 
1002 bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr)
1003 {
1004  assert(fop == SLO_LOAD);
1005  assert(dft == DFT_GAME_FILE || (lf == nullptr && dft == DFT_OLD_GAME_FILE));
1006  GameMode ogm = _game_mode;
1007 
1008  _game_mode = newgm;
1009 
1010  switch (lf == nullptr ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
1011  case SL_OK: return true;
1012 
1013  case SL_REINIT:
1014  if (_network_dedicated) {
1015  /*
1016  * We need to reinit a network map...
1017  * We can't simply load the intro game here as that game has many
1018  * special cases which make clients desync immediately. So we fall
1019  * back to just generating a new game with the current settings.
1020  */
1021  DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
1022  MakeNewGame(false, true);
1023  return false;
1024  }
1025  if (_network_server) {
1026  /* We can't load the intro game as server, so disconnect first. */
1028  }
1029 
1030  switch (ogm) {
1031  default:
1032  case GM_MENU: LoadIntroGame(); break;
1033  case GM_EDITOR: MakeNewEditorWorld(); break;
1034  }
1035  return false;
1036 
1037  default:
1038  _game_mode = ogm;
1039  return false;
1040  }
1041 }
1042 
1043 void SwitchToMode(SwitchMode new_mode)
1044 {
1045  /* If we are saving something, the network stays in his current state */
1046  if (new_mode != SM_SAVE_GAME) {
1047  /* If the network is active, make it not-active */
1048  if (_networking) {
1049  if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1050  NetworkReboot();
1051  } else {
1053  }
1054  }
1055 
1056  /* If we are a server, we restart the server */
1057  if (_is_network_server) {
1058  /* But not if we are going to the menu */
1059  if (new_mode != SM_MENU) {
1060  /* check if we should reload the config */
1062  LoadFromConfig();
1063  MakeNewgameSettingsLive();
1064  ResetGRFConfig(false);
1065  }
1066  NetworkServerStart();
1067  } else {
1068  /* This client no longer wants to be a network-server */
1069  _is_network_server = false;
1070  }
1071  }
1072  }
1073 
1074  /* Make sure all AI controllers are gone at quitting game */
1075  if (new_mode != SM_SAVE_GAME) AI::KillAll();
1076 
1077  switch (new_mode) {
1078  case SM_EDITOR: // Switch to scenario editor
1079  MakeNewEditorWorld();
1080  break;
1081 
1082  case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1083  case SM_NEWGAME: // New Game --> 'Random game'
1084  if (_network_server) {
1086  }
1087  MakeNewGame(false, new_mode == SM_NEWGAME);
1088  break;
1089 
1090  case SM_LOAD_GAME: { // Load game, Play Scenario
1091  ResetGRFConfig(true);
1093 
1096  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1097  } else {
1099  /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1101  }
1102  /* Update the local company for a loaded game. It is either always
1103  * company #1 (eg 0) or in the case of a dedicated server a spectator */
1105  /* Execute the game-start script */
1106  IConsoleCmdExec("exec scripts/game_start.scr 0");
1107  /* Decrease pause counter (was increased from opening load dialog) */
1109  if (_network_server) {
1111  }
1112  }
1113  break;
1114  }
1115 
1116  case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1117  if (_network_server) {
1119  }
1120  MakeNewGame(true, true);
1121  break;
1122 
1123  case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1125 
1128  break;
1129 
1130  case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1134  /* Cancel the saveload pausing */
1136  } else {
1138  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1139  }
1140  break;
1141  }
1142 
1143  case SM_MENU: // Switch to game intro menu
1144  LoadIntroGame();
1145  if (BaseSounds::ini_set == nullptr && BaseSounds::GetUsedSet()->fallback) {
1146  ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1148  }
1149  break;
1150 
1151  case SM_SAVE_GAME: // Save game.
1152  /* Make network saved games on pause compatible to singleplayer */
1155  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1156  } else {
1158  }
1159  break;
1160 
1161  case SM_SAVE_HEIGHTMAP: // Save heightmap.
1164  break;
1165 
1166  case SM_GENRANDLAND: // Generate random land within scenario editor
1169  /* XXX: set date */
1171  break;
1172 
1173  default: NOT_REACHED();
1174  }
1175 }
1176 
1177 
1184 static void CheckCaches()
1185 {
1186  /* Return here so it is easy to add checks that are run
1187  * always to aid testing of caches. */
1188  if (_debug_desync_level <= 1) return;
1189 
1190  /* Check the town caches. */
1191  std::vector<TownCache> old_town_caches;
1192  for (const Town *t : Town::Iterate()) {
1193  old_town_caches.push_back(t->cache);
1194  }
1195 
1196  extern void RebuildTownCaches();
1199 
1200  uint i = 0;
1201  for (Town *t : Town::Iterate()) {
1202  if (MemCmpT(old_town_caches.data() + i, &t->cache) != 0) {
1203  DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
1204  }
1205  i++;
1206  }
1207 
1208  /* Check company infrastructure cache. */
1209  std::vector<CompanyInfrastructure> old_infrastructure;
1210  for (const Company *c : Company::Iterate()) old_infrastructure.push_back(c->infrastructure);
1211 
1212  extern void AfterLoadCompanyStats();
1214 
1215  i = 0;
1216  for (const Company *c : Company::Iterate()) {
1217  if (MemCmpT(old_infrastructure.data() + i, &c->infrastructure) != 0) {
1218  DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
1219  }
1220  i++;
1221  }
1222 
1223  /* Strict checking of the road stop cache entries */
1224  for (const RoadStop *rs : RoadStop::Iterate()) {
1225  if (IsStandardRoadStopTile(rs->xy)) continue;
1226 
1227  assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
1228  rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
1229  rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
1230  }
1231 
1232  for (Vehicle *v : Vehicle::Iterate()) {
1233  extern void FillNewGRFVehicleCache(const Vehicle *v);
1234  if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1235 
1236  uint length = 0;
1237  for (const Vehicle *u = v; u != nullptr; u = u->Next()) length++;
1238 
1239  NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1240  VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1241  GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
1242  TrainCache *tra_cache = CallocT<TrainCache>(length);
1243 
1244  length = 0;
1245  for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1247  grf_cache[length] = u->grf_cache;
1248  veh_cache[length] = u->vcache;
1249  switch (u->type) {
1250  case VEH_TRAIN:
1251  gro_cache[length] = Train::From(u)->gcache;
1252  tra_cache[length] = Train::From(u)->tcache;
1253  break;
1254  case VEH_ROAD:
1255  gro_cache[length] = RoadVehicle::From(u)->gcache;
1256  break;
1257  default:
1258  break;
1259  }
1260  length++;
1261  }
1262 
1263  switch (v->type) {
1264  case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
1267  case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
1268  default: break;
1269  }
1270 
1271  length = 0;
1272  for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1274  if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1275  DEBUG(desync, 2, "newgrf cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
1276  }
1277  if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1278  DEBUG(desync, 2, "vehicle cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
1279  }
1280  switch (u->type) {
1281  case VEH_TRAIN:
1282  if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1283  DEBUG(desync, 2, "train ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1284  }
1285  if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1286  DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1287  }
1288  break;
1289  case VEH_ROAD:
1290  if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1291  DEBUG(desync, 2, "road vehicle ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1292  }
1293  break;
1294  default:
1295  break;
1296  }
1297  length++;
1298  }
1299 
1300  free(grf_cache);
1301  free(veh_cache);
1302  free(gro_cache);
1303  free(tra_cache);
1304  }
1305 
1306  /* Check whether the caches are still valid */
1307  for (Vehicle *v : Vehicle::Iterate()) {
1308  byte buff[sizeof(VehicleCargoList)];
1309  memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1310  v->cargo.InvalidateCache();
1311  assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1312  }
1313 
1314  /* Backup stations_near */
1315  std::vector<StationList> old_town_stations_near;
1316  for (Town *t : Town::Iterate()) old_town_stations_near.push_back(t->stations_near);
1317 
1318  std::vector<StationList> old_industry_stations_near;
1319  for (Industry *ind : Industry::Iterate()) old_industry_stations_near.push_back(ind->stations_near);
1320 
1321  for (Station *st : Station::Iterate()) {
1322  for (CargoID c = 0; c < NUM_CARGO; c++) {
1323  byte buff[sizeof(StationCargoList)];
1324  memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
1325  st->goods[c].cargo.InvalidateCache();
1326  assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
1327  }
1328 
1329  /* Check docking tiles */
1330  TileArea ta;
1331  std::map<TileIndex, bool> docking_tiles;
1332  TILE_AREA_LOOP(tile, st->docking_station) {
1333  ta.Add(tile);
1334  docking_tiles[tile] = IsDockingTile(tile);
1335  }
1336  UpdateStationDockingTiles(st);
1337  if (ta.tile != st->docking_station.tile || ta.w != st->docking_station.w || ta.h != st->docking_station.h) {
1338  DEBUG(desync, 2, "station docking mismatch: station %i, company %i", st->index, (int)st->owner);
1339  }
1340  TILE_AREA_LOOP(tile, ta) {
1341  if (docking_tiles[tile] != IsDockingTile(tile)) {
1342  DEBUG(desync, 2, "docking tile mismatch: tile %i", (int)tile);
1343  }
1344  }
1345 
1346  /* Check industries_near */
1347  IndustryList industries_near = st->industries_near;
1348  st->RecomputeCatchment();
1349  if (st->industries_near != industries_near) {
1350  DEBUG(desync, 2, "station industries near mismatch: station %i", st->index);
1351  }
1352  }
1353 
1354  /* Check stations_near */
1355  i = 0;
1356  for (Town *t : Town::Iterate()) {
1357  if (t->stations_near != old_town_stations_near[i]) {
1358  DEBUG(desync, 2, "town stations near mismatch: town %i", t->index);
1359  }
1360  i++;
1361  }
1362  i = 0;
1363  for (Industry *ind : Industry::Iterate()) {
1364  if (ind->stations_near != old_industry_stations_near[i]) {
1365  DEBUG(desync, 2, "industry stations near mismatch: industry %i", ind->index);
1366  }
1367  i++;
1368  }
1369 }
1370 
1377 {
1378  /* don't execute the state loop during pause */
1379  if (_pause_mode != PM_UNPAUSED) {
1387 
1389 #ifndef DEBUG_DUMP_COMMANDS
1390  Game::GameLoop();
1391 #endif
1392  return;
1393  }
1394 
1395  PerformanceMeasurer framerate(PFE_GAMELOOP);
1397  if (HasModalProgress()) return;
1398 
1400 
1401  if (_game_mode == GM_EDITOR) {
1403  RunTileLoop();
1404  CallVehicleTicks();
1405  CallLandscapeTick();
1408 
1410  NewsLoop();
1411  } else {
1412  if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
1413  /* Save the desync savegame if needed. */
1414  char name[MAX_PATH];
1415  seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
1417  }
1418 
1419  CheckCaches();
1420 
1421  /* All these actions has to be done from OWNER_NONE
1422  * for multiplayer compatibility */
1423  Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1424 
1427  IncreaseDate();
1428  RunTileLoop();
1429  CallVehicleTicks();
1430  CallLandscapeTick();
1432 
1433 #ifndef DEBUG_DUMP_COMMANDS
1434  {
1436  AI::GameLoop();
1437  Game::GameLoop();
1438  }
1439 #endif
1441 
1443  NewsLoop();
1444  cur_company.Restore();
1445  }
1446 
1447  assert(IsLocalCompany());
1448 }
1449 
1454 static void DoAutosave()
1455 {
1456  char buf[MAX_PATH];
1457 
1459  GenerateDefaultSaveName(buf, lastof(buf));
1460  strecat(buf, ".sav", lastof(buf));
1461  } else {
1462  static int _autosave_ctr = 0;
1463 
1464  /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1465  seprintf(buf, lastof(buf), "autosave%d.sav", _autosave_ctr);
1466 
1467  if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
1468  }
1469 
1470  DEBUG(sl, 2, "Autosaving to '%s'", buf);
1472  ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
1473  }
1474 }
1475 
1476 void GameLoop()
1477 {
1478  if (_game_mode == GM_BOOTSTRAP) {
1479  /* Check for UDP stuff */
1481  InputLoop();
1482  return;
1483  }
1484 
1486 
1487  /* autosave game? */
1488  if (_do_autosave) {
1489  DoAutosave();
1490  _do_autosave = false;
1492  }
1493 
1494  /* switch game mode? */
1495  if (_switch_mode != SM_NONE && !HasModalProgress()) {
1496  SwitchToMode(_switch_mode);
1497  _switch_mode = SM_NONE;
1498  }
1499 
1500  IncreaseSpriteLRU();
1501  InteractiveRandom();
1502 
1503  /* Check for UDP stuff */
1505 
1506  if (_networking && !HasModalProgress()) {
1507  /* Multiplayer */
1508  NetworkGameLoop();
1509  } else {
1510  if (_network_reconnect > 0 && --_network_reconnect == 0) {
1511  /* This means that we want to reconnect to the last host
1512  * We do this here, because it means that the network is really closed */
1514  }
1515  /* Singleplayer */
1516  StateGameLoop();
1517  }
1518 
1519  if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1520 
1521  InputLoop();
1522 
1524  MusicLoop();
1525 }
bool disable_elrails
when true, the elrails are disabled
FiosType
Elements of a file system that are recognized.
Definition: fileio_type.h:67
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows. ...
Definition: main_gui.cpp:552
Functions related to OTTD&#39;s strings.
void UpdateLandscapingLimits()
Update the landscaping limits per company.
Owner
Enum for all companies/owners.
Definition: company_type.h:18
char * _ini_videodriver
The video driver a stored in the configuration file.
Definition: driver.cpp:19
Road vehicle states.
All pool types.
Definition: pool_type.hpp:23
VehicleSettings vehicle
options for vehicles
Cached often queried (NewGRF) values.
Definition: vehicle_base.h:65
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:43
Time spent processing cargo movement.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:80
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
Definition: strings.cpp:2097
void ParseConnectionString(const char **company, const char **port, char *connection_string)
Converts a string to ip/port/company Format: IP:port::company.
Definition: network.cpp:461
bool _networking
are we in networking mode?
Definition: network.cpp:52
Base of all video drivers.
void InitializeScreenshotFormats()
Initialize screenshot format information on startup, with _screenshot_format_name filled from the loa...
Definition: screenshot.cpp:580
#define GETOPT_SHORT_OPTVAL(shortname)
Short option with optional value.
Definition: getoptdata.h:104
void CheckEngines()
Check for engines that have an appropriate availability.
Definition: engine.cpp:1190
Scan for base sets.
Definition: fileio_func.h:98
Company * DoStartupNewCompany(bool is_ai, CompanyID company=INVALID_COMPANY)
Create a new company and sets all company variables default values.
bool _blitter_autodetected
Was the blitter autodetected or specified by the user?
Definition: driver.cpp:29
FiosType FiosGetSavegameListCallback(SaveLoadOperation fop, const char *file, const char *ext, char *title, const char *last)
Callback for FiosGetFileList.
Definition: fios.cpp:459
virtual void MainLoop()
Called once every tick.
bool HandleBootstrap()
Handle all procedures for bootstrapping OpenTTD without a base graphics set.
FILE * _log_fd
File to reroute output of a forked OpenTTD to.
Definition: dedicated.cpp:13
#define GETOPT_SHORT_VALUE(shortname)
Short option with value.
Definition: getoptdata.h:97
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3218
static int MemCmpT(const T *ptr1, const T *ptr2, size_t num=1)
Type-safe version of memcmp().
Definition: mem_func.hpp:63
int openttd_main(int argc, char *argv[])
Main entry point for this lovely game.
Definition: openttd.cpp:534
static char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: depend.cpp:97
void SetDParamStr(uint n, const char *str)
Set a rawstring parameter.
Definition: error_gui.cpp:160
Base class for roadstops.
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
bool keep_all_autosave
name the autosave in a different way
uint16 last_port
port of the last joined server
Load heightmap from scenario editor.
Definition: openttd.h:36
#define GETOPT_SHORT_NOVAL(shortname)
Short option without value.
Definition: getoptdata.h:91
void GenerateDefaultSaveName(char *buf, const char *last)
Fill the buffer with the default name for a savegame or screenshot.
Definition: saveload.cpp:2830
static void GameLoop()
Called every game-tick to let Game do something.
Definition: game_core.cpp:31
Saveload window; Window numbers:
Definition: window_type.h:137
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
Definition: saveload.h:29
GameConfig stores the configuration settings of every Game.
byte _display_opt
What do we want to draw/do?
void AfterLoadCompanyStats()
Rebuilding of company statistics after loading a savegame.
Definition: company_sl.cpp:94
Train vehicle type.
Definition: vehicle_type.h:24
CargoList that is used for stations.
Definition: cargopacket.h:448
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:329
struct LoggedAction * gamelog_action
Gamelog actions.
Definition: fios.h:46
Switch to game intro menu.
Definition: openttd.h:30
void SetName(const char *name)
Set the name of the file.
Definition: saveload.cpp:2892
static uint FindSets()
Do the scan for files.
Hotkey related functions.
Functions related to dates.
Northwest.
Generate a map for a new game.
Definition: genworld.h:28
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:407
Load game, Play Scenario.
Definition: openttd.h:29
static const OptionData _options[]
Options of OpenTTD.
Definition: openttd.cpp:499
Base for the train class.
bool pause_on_newgame
whether to start new games paused or not
Functions/types related to the road GUIs.
Ship vehicle type.
Definition: vehicle_type.h:26
bool * save_config_ptr
The pointer to the save config setting.
Definition: openttd.cpp:398
static char * GetConsoleList(char *p, const char *last, bool newest_only=false)
Wrapper function for AIScanner::GetAIConsoleList.
Definition: ai_core.cpp:318
Maximal number of cargo types in a game.
Definition: cargo_type.h:64
Functions to be called to log possibly unsafe game events.
Types for recording game performance data.
Generic functions for replacing base data (graphics, sounds).
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:58
void InitWindowSystem()
(re)initialize the windowing system
Definition: window.cpp:1896
static void Paused(PerformanceElement elem)
Indicate that a cycle of "pause" where no processing occurs.
static void Uninitialize(bool keepConfig)
Uninitialize the Game system.
Definition: game_core.cpp:97
void RebuildTownCaches()
Rebuild all the cached variables of towns.
Definition: town_sl.cpp:25
int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
Safer implementation of vsnprintf; same as vsnprintf except:
Definition: string.cpp:60
The client wants a new company.
Definition: company_type.h:34
Functions related to vehicles.
char * md5sumToString(char *buf, const char *last, const uint8 md5sum[16])
Convert the md5sum to a hexadecimal string representation.
Definition: string.cpp:425
SaveLoadVersion _sl_version
the major savegame version identifier
Definition: saveload.cpp:61
static void ShutdownDrivers()
Shuts down all active drivers.
Definition: driver.h:113
char title[255]
Internal name of the game.
Definition: saveload.h:322
MusicSettings music
settings related to music/sound
Base for all sound drivers.
static void Initialize()
Initialize the AI system.
Definition: ai_core.cpp:161
Vehicle data structure.
Definition: vehicle_base.h:210
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.
GRFConfig * grfconfig
NewGrf configuration from save.
Definition: fios.h:43
void FioCloseAll()
Close all slotted open files.
Definition: fileio.cpp:211
static const Year INVALID_YEAR
Representation of an invalid year.
Definition: date_type.h:109
Defines the internal data of a functional industry.
Definition: industry.h:40
Wrapper for (un)resolved network addresses; there&#39;s no reason to transform a numeric IP to a string a...
Definition: address.h:27
Generate a newgame from a heightmap.
Definition: genworld.h:31
static void Clean(PoolType)
Clean all pools of given type.
Definition: pool_func.cpp:30
Tindex index
Index of this pool item.
Definition: pool_type.hpp:227
void NetworkStartUp()
This tries to launch the network for a given OS.
Definition: network.cpp:1051
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.
Definition: error_gui.cpp:380
Cached often queried values common to all vehicles.
Definition: vehicle_base.h:120
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:21
uint16 dedicated_port
Port for the dedicated server.
Definition: openttd.cpp:394
Data of an option.
Definition: getoptdata.h:22
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:2820
Base for aircraft.
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Functions related to world/map generation.
static char * GetDriversInfo(char *p, const char *last)
Build a human readable list of available drivers, grouped by type.
Definition: driver.cpp:188
Functions to make screenshots.
bool UpdateNewGRFConfigPalette(int32 p1)
Update the palettes of the graphics from the config file.
bool reload_cfg
reload the config file before restarting
static bool SetSet(const char *name)
Set the set to be used.
static bool IsStandardRoadStopTile(TileIndex t)
Is tile t a standard (non-drive through) road stop station?
Definition: station_map.h:223
void SaveToConfig()
Save the values to the configuration file.
Definition: settings.cpp:1750
Base set has 8 bpp sprites only.
int32 Year
Type for the year, note: 0 based, i.e. starts at the year 0.
Definition: date_type.h:18
uint8 map_x
X size of map.
RAII class for measuring simple elements of performance.
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:116
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:24
uint32 last_newgrf_count
the numbers of NewGRFs we found during the last scan
Functions related to laying out the texts.
byte vehstatus
Status.
Definition: vehicle_base.h:315
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:25
Cached, frequently calculated values.
uint16 w
The width of the area.
Definition: tilearea_type.h:18
Time spent processing aircraft.
static void Reset(PerformanceElement elem)
Store the previous accumulator value and reset for a new cycle of accumulating measurements.
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
void InputLoop()
Regular call from the global game loop.
Definition: window.cpp:3087
CompanySettings settings
settings specific for each company
Definition: company_base.h:127
const char * GetSaveLoadErrorString()
Get the string representation of the error message.
Definition: saveload.cpp:2444
File is being saved.
Definition: fileio_type.h:50
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Speed of gameloop processing.
Functions/types etc.
Load file for checking and/or preview.
Definition: fileio_type.h:48
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:24
static uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition: math_func.hpp:182
bool _network_available
is network mode available?
Definition: network.cpp:54
Variables that are cached to improve performance and such.
Definition: train.h:69
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:55
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
static char * GetConsoleList(char *p, const char *last, bool newest_only=false)
Wrapper function for GameScanner::GetConsoleList.
Definition: game_core.cpp:228
static void CheckCaches()
Check the validity of some of the caches.
Definition: openttd.cpp:1184
Functions related to (drawing on) viewports.
Pseudo random number generator.
uint8 map_y
Y size of map.
void InitFreeType(bool monospace)
(Re)initialize the freetype related things, i.e.
Definition: fontcache.cpp:1034
Library for parsing command-line options.
std::mutex _modal_progress_work_mutex
Rights for the performing work.
Definition: progress.cpp:21
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition: saveload.cpp:402
void CDECL ShowInfoF(const char *str,...)
Shows some information on the console/a popup box depending on the OS.
Definition: openttd.cpp:135
Save game or scenario file.
Definition: fileio_type.h:31
Interface for filtering a savegame till it is loaded.
old or new savegame
Definition: fileio_type.h:18
old or new scenario
Definition: fileio_type.h:19
Functions to read fonts from files and cache them.
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:24
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:279
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition: fios_gui.cpp:38
Tile animation!
static char * GetBlittersInfo(char *p, const char *last)
Fill a buffer with information about the blitters.
Definition: factory.hpp:156
Callback structure of statements to be executed after the NewGRF scan.
Definition: openttd.cpp:390
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.
Definition: gamelog.cpp:806
NetworkSettings network
settings related to the network
Vehicle is crashed.
Definition: vehicle_base.h:37
bool _is_network_server
Does this client wants to be a network-server?
Definition: network.cpp:56
The tile has no ownership.
Definition: company_type.h:25
void UpdateCache()
Update the caches of this ship.
Definition: ship_cmd.cpp:202
void GamelogReset()
Resets and frees all memory allocated - used before loading or starting a new game.
Definition: gamelog.cpp:115
Functions/types related to saving and loading games.
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:431
void MusicLoop()
Check music playback status and start/stop/song-finished.
Definition: music_gui.cpp:424
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
Definition: genworld.cpp:301
A music driver, needs to be before sound to properly shut down extmidi forked music players...
Definition: driver.h:41
Functions related to errors.
Load a heightmap and start a new game from it.
Definition: openttd.h:35
char * _ini_blitter
The blitter as stored in the configuration file.
Definition: driver.cpp:28
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:289
virtual void SetVolume(byte vol)=0
Set the volume, if possible.
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Definition: tilearea.cpp:43
Switch to scenario editor.
Definition: openttd.h:28
DateFract _date_fract
Fractional part of the day.
Definition: date.cpp:28
static void GameLoop()
Called every game-tick to let AIs do something.
Definition: ai_core.cpp:67
SaveOrLoadResult
Save or load result codes.
Definition: saveload.h:310
static void ShowHelp()
Show the help message when someone passed a wrong parameter.
Definition: openttd.cpp:148
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
A normal unpaused game.
Definition: openttd.h:56
The client is spectating.
Definition: company_type.h:35
virtual void Stop()=0
Stop this driver.
CompanySettings company
default values for per-company settings
Information about GRF, used in the game and (part of it) in savegames.
char * _ini_sounddriver
The sound driver a stored in the configuration file.
Definition: driver.cpp:24
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition: train_cmd.cpp:106
GameMode
Mode which defines the state of the game.
Definition: openttd.h:16
Old save game or scenario file.
Definition: fileio_type.h:30
VehicleDefaultSettings vehicle
default settings for vehicles
Functions related to engines.
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...
static void Uninitialize(bool keepConfig)
Uninitialize the AI system.
Definition: ai_core.cpp:175
static Blitter * SelectBlitter(const char *name)
Find the requested blitter and return his class.
Definition: factory.hpp:94
A game paused for saving/loading.
Definition: openttd.h:58
Time spend processing road vehicles.
void InitializeRoadGUI()
I really don&#39;t know why rail_gui.cpp has this too, shouldn&#39;t be included in the other one...
Definition: road_gui.cpp:1262
Functions related to setting/changing the settings.
static const uint16 NETWORK_DEFAULT_DEBUGLOG_PORT
The default port debug-log is sent to (TCP)
Definition: config.h:31
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:79
Functions related to modal progress.
A path without any base directory.
Definition: fileio_type.h:125
virtual void OnNewGRFsScanned()
Called whenever the NewGRF scan completed.
Definition: openttd.cpp:417
Base for all music playback.
#define TILE_AREA_LOOP(var, ta)
A loop which iterates over the tiles of a TileArea.
Definition of base types and functions in a cross-platform compatible way.
Enter the gameloop, changes will be permanent.
char * _config_file
Configuration file of OpenTTD.
Definition: settings.cpp:83
void Clear()
Reset read data.
Definition: fios_gui.cpp:47
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:93
A number of safeguards to prevent using unsafe methods.
void StateGameLoop()
State controlling game loop.
Definition: openttd.cpp:1376
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...
Declaration of link graph schedule used for cargo distribution.
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition: settings.cpp:81
static void SaveToConfig()
Save all WindowDesc settings to _windows_file.
Definition: window.cpp:164
uint8 _network_reconnect
Reconnect timeout.
Definition: network.cpp:62
void FillNewGRFVehicleCache(const Vehicle *v)
Fill the grf_cache of the given vehicle.
static bool IsDockingTile(TileIndex t)
Checks whether the tile is marked as a dockling tile.
Definition: water_map.h:365
Scan for scenarios and heightmaps.
Definition: fileio_func.h:101
Base directory for all savegames.
Definition: fileio_type.h:110
Subdirectory of save for autosaves.
Definition: fileio_type.h:111
const char * join_server_password
The password to join the server with.
Definition: openttd.cpp:396
byte starting_colour
default color scheme for the company to start a new game with
static AIConfig * GetConfig(CompanyID company, ScriptSettingSource source=SSS_DEFAULT)
Get the config of a company.
Definition: ai_config.cpp:45
Represents the covered area of e.g.
Definition: tilearea_type.h:16
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:136
AfterNewGRFScan(bool *save_config_ptr)
Create a new callback.
Definition: openttd.cpp:406
void LoadFromConfig(bool minimal)
Load the values from the configuration files.
Definition: settings.cpp:1720
Console functions used outside of the console code.
char * error_data
Data to pass to SetDParamStr when displaying error.
Definition: fios.h:34
#define GETOPT_END()
Option terminator.
Definition: getoptdata.h:107
void ScheduleErrorMessage(const ErrorMessageData &data)
Schedule an error.
Definition: error_gui.cpp:442
char * DumpDebugFacilityNames(char *buf, char *last)
Dump the available debug facility names in the help text.
Definition: debug.cpp:84
A sound driver.
Definition: driver.h:42
static void ShutdownGame()
Uninitializes drivers, frees allocated memory, cleans pools, ...
Definition: openttd.cpp:286
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
Definition: gfx_type.h:120
SaveOrLoadResult LoadWithFilter(LoadFilter *reader)
Load the game using a (reader) filter.
Definition: saveload.cpp:2713
const char * join_company_password
The password to join the company with.
Definition: openttd.cpp:397
bool HasErrors()
Check whether loading the game resulted in errors.
Definition: fios.h:67
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?"
A game normally paused.
Definition: openttd.h:57
void CheckIndustries()
Verify whether the generated industries are complete, and warn the user if not.
Generate an empty map (sea-level)
Definition: genworld.h:29
static MusicDriver * GetInstance()
Get the currently active instance of the music driver.
char * opt
Option value, if available (else nullptr).
Definition: getoptdata.h:31
Basic functions/variables used all over the place.
Time spent processing other world features.
SaveOrLoadResult SaveOrLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
Definition: saveload.cpp:2733
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:271
void NetworkShutDown()
This shuts the network down.
Definition: network.cpp:1072
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Definition: command.cpp:536
NetworkServerGameInfo _network_game_info
Information about our game.
Definition: network.cpp:57
bool save_config
The save config setting.
Definition: openttd.cpp:399
File is being loaded.
Definition: fileio_type.h:49
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:47
void InitializeLanguagePacks()
Make a list of the available language packs.
Definition: strings.cpp:1949
bool _use_threaded_modal_progress
Threading usable for modal progress?
Definition: progress.cpp:19
StringID error
Error message from loading. INVALID_STRING_ID if no error.
Definition: fios.h:33
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:592
void WaitTillGeneratedWorld()
This will wait for the thread to finish up his work.
Definition: genworld.cpp:247
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:47
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
Definition: window.cpp:3351
void UnInitWindowSystem()
Close down the windowing system.
Definition: window.cpp:1917
class GameConfig * game_config
settings for gamescript
Save game.
Definition: openttd.h:31
Functions to be called to log a crash.
char * dedicated_host
Hostname for the dedicated server.
Definition: openttd.cpp:393
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
Definition: fileio.cpp:622
StringID name
The name for this object.
Definition: newgrf_object.h:62
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:17
static void Initialize()
Initialize the Game system.
Definition: game_core.cpp:57
char map_name[NETWORK_NAME_LENGTH]
Map which is played ["random" for a randomized map].
Definition: game.h:25
uint16 server_port
port the server listens on
static SoundDriver * GetInstance()
Get the currently active instance of the sound driver.
void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
Delete a window by its class and window number (if it is open).
Definition: window.cpp:1165
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done...
Definition: genworld.cpp:228
Callback for NewGRF scanning.
byte music_vol
The requested music volume.
void IncreaseDate()
Increases the tick counter, increases date and possibly calls procedures that have to be called daily...
Definition: date.cpp:269
void LoadHotkeysFromConfig()
Load the hotkeys from the config file.
Definition: hotkeys.cpp:349
Functions related to companies.
No support for 8bpp by OS or hardware, force 32bpp blitters.
Definition: gfx_type.h:316
An invalid company.
Definition: company_type.h:30
static const uint16 NETWORK_DEFAULT_PORT
The default port of the game server (TCP & UDP)
Definition: config.h:29
The data of the error message.
Definition: error.h:28
Leave the gameloop, changes will be temporary.
uint32 generation_seed
noise seed for world generation
Declaration of functions and types defined in highscore.h and highscore_gui.h.
Data storage for parsing command line options.
Definition: getoptdata.h:30
GUISettings gui
settings related to the GUI
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:378
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
Definition: engine.cpp:527
CargoList that is used for vehicles.
Definition: cargopacket.h:268
Time spent processing ships.
void DeterminePaths(const char *exe)
Acquire the base paths (personal dir and game data dir), fill all other paths (save dir...
Definition: fileio.cpp:1139
static void DoAutosave()
Create an autosave.
Definition: openttd.cpp:1454
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:57
static void SelectDriver(const char *name, Driver::Type type)
Find the requested driver and return its class.
Definition: driver.cpp:85
void ResetNewGRFData()
Reset all NewGRF loaded data.
Definition: newgrf.cpp:8556
Declarations for savegames operations.
void IConsoleCmdExec(const char *cmdstr, const uint recurse_count)
Execute a given command passed to us.
Definition: console.cpp:407
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:579
First company, same as owner.
Definition: company_type.h:22
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
byte colour
Company colour.
Definition: company_base.h:69
static void KillAll()
Kill any and all AIs we manage.
Definition: ai_core.cpp:151
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
Definition: window.cpp:141
Restart –> &#39;Random game&#39; with current settings.
Definition: openttd.h:27
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:113
static char * GetSetsList(char *p, const char *last)
Returns a list with the sets.
void ResetGRFConfig(bool defaults)
Reset the current GRF Config to either blank or newgame settings.
char * network_conn
Information about the server to connect to, or nullptr.
Definition: openttd.cpp:395
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition: subsidy.cpp:131
static void Clear()
Clear all link graphs and jobs from the schedule.
virtual void MainLoop()=0
Perform the actual drawing.
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:66
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:52
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Definition: settings.cpp:82
Maximum number of companies.
Definition: company_type.h:23
Town data structure.
Definition: town.h:53
bool in_window
mouse inside this window, determines drawing logic
Definition: gfx_type.h:141
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:46
char default_company_pass[NETWORK_PASSWORD_LENGTH]
default password for new companies in encrypted form
uint gamelog_actions
Number of gamelog actions.
Definition: fios.h:47
The normal zoom level.
Definition: zoom_type.h:22
void ScanNewGRFFiles(NewGRFScanCallback *callback)
Scan for all NewGRFs.
Statusbar (at the bottom of your screen); Window numbers:
Definition: window_type.h:57
Base functions for all Games.
Functions related to commands.
Network functions used by other parts of OpenTTD.
char name[MAX_PATH]
Name of the file.
Definition: saveload.h:321
bool _network_server
network-server is active
Definition: network.cpp:53
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:318
A Stop for a Road Vehicle.
Definition: roadstop_base.h:22
static void ReduceLineCache()
Reduce the size of linecache if necessary to prevent infinite growth.
Definition: gfx_layout.cpp:908
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
Definition: hotkeys.cpp:355
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:45
void UninitFreeType()
Free everything allocated w.r.t.
Definition: fontcache.cpp:1053
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
Definition: rail_gui.cpp:1979
Perform palette animation.
Definition: openttd.h:44
static void LoadIntroGame(bool load_newgrfs=true)
Load the introduction game.
Definition: openttd.cpp:321
class AIConfig * ai_config[MAX_COMPANIES]
settings per company
Colours _company_colours[MAX_COMPANIES]
NOSAVE: can be determined from company structs.
Definition: company_cmd.cpp:46
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer...
Definition: network.cpp:837
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Definition: saveload.h:320
byte max_num_autosaves
controls how many autosavegames are made before the game starts to overwrite (names them 0 to max_num...
bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=nullptr)
Load the specified savegame but on error do different things.
Definition: openttd.cpp:1002
header file for electrified rail specific functions
A video driver.
Definition: driver.h:43
int GetOpt()
Find the next option.
Definition: getoptdata.cpp:22
Base for ships.
void NetworkDisconnect(bool blocking, bool close_admins)
We want to disconnect from the host/clients.
Definition: network.cpp:781
Load scenario from scenario editor.
Definition: openttd.h:34
uint32 generation_seed
Seed for the new game.
Definition: openttd.cpp:392
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
Base of all industries.
Aircraft vehicle type.
Definition: vehicle_type.h:27
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:129
static void ParseResolution(Dimension *res, const char *s)
Extract the resolution from the given string and store it in the &#39;res&#39; parameter. ...
Definition: openttd.cpp:269
char last_host[NETWORK_HOSTNAME_LENGTH]
IP address of the last joined server.
declaration of OTTD revision dependent variables
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
bool HasNewGrfs()
Check whether the game uses any NewGrfs.
Definition: fios.h:76
completed successfully
Definition: saveload.h:311
void InitializeSpriteSorter()
Choose the "best" sprite sorter and set _vp_sprite_sorter.
Definition: viewport.cpp:3385
Types related to sprite sorting.
void Restore()
Restore the variable.
Base functions for all AIs.
char * _ini_musicdriver
The music driver a stored in the configuration file.
Definition: driver.cpp:26
Base of the town class.
std::mutex _modal_progress_paint_mutex
Rights for the painting.
Definition: progress.cpp:23
Northeast, upper right on your monitor.
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every 256 ticks...
Definition: landscape.cpp:801
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches) ...
Definition: newgrf_config.h:25
GameCreationSettings game_creation
settings used during the creation of a game (map)
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...
Definition: saveload.cpp:2863
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:20
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
Definition: saveload.h:319
void SetDebugString(const char *s)
Set debugging levels by parsing the text in s.
Definition: debug.cpp:172
StringList _network_bind_list
The addresses to bind on.
Definition: network.cpp:63
Generate random land within scenario editor.
Definition: openttd.h:33
AIConfig stores the configuration settings of every AI.
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition: window.cpp:1937
int numleft
Number of arguments left in argv.
Definition: getoptdata.h:32
const char * NetworkChangeCompanyPassword(CompanyID company_id, const char *password)
Change the company password of a given company.
Definition: network.cpp:162
GUI functions that shouldn&#39;t be here.
Functions related to news.
void SaveToHighScore()
Save HighScore table to file.
Definition: highscore.cpp:124
bool MakeHeightmapScreenshot(const char *filename)
Make a heightmap of the current map.
Definition: screenshot.cpp:821
Base classes/functions for stations.
Errors (eg. saving/loading failed)
Definition: error.h:23
Date _date
Current date in days (day counter)
Definition: date.cpp:27
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company&#39;s primary colour.
uint16 h
The height of the area.
Definition: tilearea_type.h:19
Get the Script config from the current game.
Year startyear
The start year.
Definition: openttd.cpp:391
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:44
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:28
Dimensions (a width and height) of a rectangle in 2D.
Valid changes while vehicle is driving, and possibly changing tracks.
Definition: train.h:48
static void SetErrorMessage(const char *message)
Sets a message for the error message handler.
Definition: crashlog.cpp:498
Generate a random map for SE.
Definition: genworld.h:30
bool _do_autosave
are we doing an autosave at the moment?
Definition: saveload.cpp:64
Year starting_year
starting date
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.
Station data structure.
Definition: station_base.h:450
Time spent processing trains.
Factory to &#39;query&#39; all available blitters.
static const GraphicsSet * GetUsedSet()
Return the used set.
Functions related to subsidies.
New Game –> &#39;Random game&#39;.
Definition: openttd.h:26
Road vehicle type.
Definition: vehicle_type.h:25
SwitchMode
Mode which defines what mode we&#39;re switching to.
Definition: openttd.h:24
static bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition: progress.h:21
void LoadFromHighScore()
Initialize the highscore table to 0 and if any file exists, load in values.
Definition: highscore.cpp:152
Save heightmap.
Definition: openttd.h:32
GroundVehicleCache gcache
Cache of often calculated values.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1600
Sum of all GS/AI scripts.
bool SettingsDisableElrail(int32 p1)
_settings_game.disable_elrail callback
Definition: elrail.cpp:592
Base for the NewGRF implementation.
static const char * ini_set
The set as saved in the config file.
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
Definition: saveload.h:313
pause the game
Definition: command_type.h:255