OpenTTD
openttd.cpp
Go to the documentation of this file.
1 /* $Id: openttd.cpp 26828 2014-09-16 17:14:07Z rubidium $ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * 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.
6  * 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.
7  * 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/>.
8  */
9 
12 #include "stdafx.h"
13 
14 #include "blitter/factory.hpp"
15 #include "sound/sound_driver.hpp"
16 #include "music/music_driver.hpp"
17 #include "video/video_driver.hpp"
18 
19 #include "fontcache.h"
20 #include "error.h"
21 #include "gui.h"
22 
23 #include "base_media_base.h"
24 #include "saveload/saveload.h"
25 #include "company_func.h"
26 #include "command_func.h"
27 #include "news_func.h"
28 #include "fios.h"
29 #include "aircraft.h"
30 #include "roadveh.h"
31 #include "train.h"
32 #include "ship.h"
33 #include "console_func.h"
34 #include "screenshot.h"
35 #include "network/network.h"
36 #include "network/network_func.h"
37 #include "ai/ai.hpp"
38 #include "ai/ai_config.hpp"
39 #include "settings_func.h"
40 #include "genworld.h"
41 #include "progress.h"
42 #include "strings_func.h"
43 #include "date_func.h"
44 #include "vehicle_func.h"
45 #include "gamelog.h"
46 #include "animated_tile_func.h"
47 #include "roadstop_base.h"
48 #include "elrail_func.h"
49 #include "rev.h"
50 #include "highscore.h"
51 #include "station_base.h"
52 #include "crashlog.h"
53 #include "engine_func.h"
54 #include "core/random_func.hpp"
55 #include "rail_gui.h"
56 #include "core/backup_type.hpp"
57 #include "hotkeys.h"
58 #include "newgrf.h"
59 #include "misc/getoptdata.h"
60 #include "game/game.hpp"
61 #include "game/game_config.hpp"
62 #include "town.h"
63 #include "subsidy_func.h"
64 #include "gfx_layout.h"
65 #include "viewport_sprite_sorter.h"
66 
68 
69 #include <stdarg.h>
70 
71 #include "safeguards.h"
72 
73 void CallLandscapeTick();
74 void IncreaseDate();
75 void DoPaletteAnimations();
76 void MusicLoop();
77 void ResetMusic();
78 void CallWindowTickEvent();
79 bool HandleBootstrap();
80 
81 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
82 extern void ShowOSErrorBox(const char *buf, bool system);
83 extern char *_config_file;
84 
90 void CDECL usererror(const char *s, ...)
91 {
92  va_list va;
93  char buf[512];
94 
95  va_start(va, s);
96  vseprintf(buf, lastof(buf), s, va);
97  va_end(va);
98 
99  ShowOSErrorBox(buf, false);
101 
102  exit(1);
103 }
104 
110 void CDECL error(const char *s, ...)
111 {
112  va_list va;
113  char buf[512];
114 
115  va_start(va, s);
116  vseprintf(buf, lastof(buf), s, va);
117  va_end(va);
118 
119  ShowOSErrorBox(buf, true);
120 
121  /* Set the error message for the crash log and then invoke it. */
123  abort();
124 }
125 
130 void CDECL ShowInfoF(const char *str, ...)
131 {
132  va_list va;
133  char buf[1024];
134  va_start(va, str);
135  vseprintf(buf, lastof(buf), str, va);
136  va_end(va);
137  ShowInfo(buf);
138 }
139 
143 static void ShowHelp()
144 {
145  char buf[8192];
146  char *p = buf;
147 
148  p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
149  p = strecpy(p,
150  "\n"
151  "\n"
152  "Command line options:\n"
153  " -v drv = Set video driver (see below)\n"
154  " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
155  " -m drv = Set music driver (see below)\n"
156  " -b drv = Set the blitter to use (see below)\n"
157  " -r res = Set resolution (for instance 800x600)\n"
158  " -h = Display this help text\n"
159  " -t year = Set starting year\n"
160  " -d [[fac=]lvl[,...]]= Debug mode\n"
161  " -e = Start Editor\n"
162  " -g [savegame] = Start new/save game immediately\n"
163  " -G seed = Set random seed\n"
164 #if defined(ENABLE_NETWORK)
165  " -n [ip:port#company]= Join network game\n"
166  " -p password = Password to join server\n"
167  " -P password = Password to join company\n"
168  " -D [ip][:port] = Start dedicated server\n"
169  " -l ip[:port] = Redirect DEBUG()\n"
170 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
171  " -f = Fork into the background (dedicated only)\n"
172 #endif
173 #endif /* ENABLE_NETWORK */
174  " -I graphics_set = Force the graphics set (see below)\n"
175  " -S sounds_set = Force the sounds set (see below)\n"
176  " -M music_set = Force the music set (see below)\n"
177  " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
178  " -x = Do not automatically save to config file on exit\n"
179  " -q savegame = Write some information about the savegame and exit\n"
180  "\n",
181  lastof(buf)
182  );
183 
184  /* List the graphics packs */
185  p = BaseGraphics::GetSetsList(p, lastof(buf));
186 
187  /* List the sounds packs */
188  p = BaseSounds::GetSetsList(p, lastof(buf));
189 
190  /* List the music packs */
191  p = BaseMusic::GetSetsList(p, lastof(buf));
192 
193  /* List the drivers */
195 
196  /* List the blitters */
198 
199  /* List the debug facilities. */
200  p = DumpDebugFacilityNames(p, lastof(buf));
201 
202  /* We need to initialize the AI, so it finds the AIs */
203  AI::Initialize();
204  p = AI::GetConsoleList(p, lastof(buf), true);
205  AI::Uninitialize(true);
206 
207  /* We need to initialize the GameScript, so it finds the GSs */
209  p = Game::GetConsoleList(p, lastof(buf), true);
210  Game::Uninitialize(true);
211 
212  /* ShowInfo put output to stderr, but version information should go
213  * to stdout; this is the only exception */
214 #if !defined(WIN32) && !defined(WIN64)
215  printf("%s\n", buf);
216 #else
217  ShowInfo(buf);
218 #endif
219 }
220 
221 static void WriteSavegameInfo(const char *name)
222 {
223  extern uint16 _sl_version;
224  uint32 last_ottd_rev = 0;
225  byte ever_modified = 0;
226  bool removed_newgrfs = false;
227 
228  GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
229 
230  char buf[8192];
231  char *p = buf;
232  p += seprintf(p, lastof(buf), "Name: %s\n", name);
233  p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
234  p += seprintf(p, lastof(buf), "NewGRF ver: 0x%08X\n", last_ottd_rev);
235  p += seprintf(p, lastof(buf), "Modified: %d\n", ever_modified);
236 
237  if (removed_newgrfs) {
238  p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
239  }
240 
241  p = strecpy(p, "NewGRFs:\n", lastof(buf));
243  for (GRFConfig *c = _load_check_data.grfconfig; c != NULL; c = c->next) {
244  char md5sum[33];
245  md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
246  p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
247  }
248  }
249 
250  /* ShowInfo put output to stderr, but version information should go
251  * to stdout; this is the only exception */
252 #if !defined(WIN32) && !defined(WIN64)
253  printf("%s\n", buf);
254 #else
255  ShowInfo(buf);
256 #endif
257 }
258 
259 
266 static void ParseResolution(Dimension *res, const char *s)
267 {
268  const char *t = strchr(s, 'x');
269  if (t == NULL) {
270  ShowInfoF("Invalid resolution '%s'", s);
271  return;
272  }
273 
274  res->width = max(strtoul(s, NULL, 0), 64UL);
275  res->height = max(strtoul(t + 1, NULL, 0), 64UL);
276 }
277 
278 
283 static void ShutdownGame()
284 {
285  IConsoleFree();
286 
287  if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
288 
290 
292 
293  /* stop the scripts */
294  AI::Uninitialize(false);
295  Game::Uninitialize(false);
296 
297  /* Uninitialize variables that are allocated dynamically */
298  GamelogReset();
299 
300 #ifdef ENABLE_NETWORK
302 #endif
303 
306 
307  /* No NewGRFs were loaded when it was still bootstrapping. */
308  if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
309 
310  /* Close all and any open filehandles */
311  FioCloseAll();
312 
313  UninitFreeType();
314 }
315 
320 static void LoadIntroGame(bool load_newgrfs = true)
321 {
322  _game_mode = GM_MENU;
323 
324  if (load_newgrfs) ResetGRFConfig(false);
325 
326  /* Setup main window */
329 
330  /* Load the default opening screen savegame */
331  if (SaveOrLoad("opntitle.dat", SL_LOAD, BASESET_DIR) != SL_OK) {
332  GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
335  } else {
337  }
338 
340  _cursor.fix_at = false;
341 
342  if (load_newgrfs) CheckForMissingSprites();
344 
345  /* Play main theme */
346  if (MusicDriver::GetInstance()->IsSongPlaying()) ResetMusic();
347 }
348 
349 void MakeNewgameSettingsLive()
350 {
351  for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
352  if (_settings_game.ai_config[c] != NULL) {
353  delete _settings_game.ai_config[c];
354  }
355  }
356  if (_settings_game.game_config != NULL) {
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] = NULL;
367  if (_settings_newgame.ai_config[c] != NULL) {
369  }
370  }
372  if (_settings_newgame.game_config != NULL) {
374  }
375 }
376 
377 void OpenBrowser(const char *url)
378 {
379  /* Make sure we only accept urls that are sure to open a browser. */
380  if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
381 
382  extern void OSOpenBrowser(const char *url);
383  OSOpenBrowser(url);
384 }
385 
391  uint16 dedicated_port;
392  char *network_conn;
393  const char *join_server_password;
394  const char *join_company_password;
396  bool save_config;
397 
405  dedicated_host(NULL), dedicated_port(0), network_conn(NULL),
407  save_config_ptr(save_config_ptr), save_config(true)
408  {
409  }
410 
411  virtual void OnNewGRFsScanned()
412  {
413  ResetGRFConfig(false);
414 
416 
417  AI::Initialize();
419 
420  /* We want the new (correct) NewGRF count to survive the loading. */
421  uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
422  LoadFromConfig();
423  _settings_client.gui.last_newgrf_count = last_newgrf_count;
424  /* Since the default for the palette might have changed due to
425  * reading the configuration file, recalculate that now. */
427 
428  Game::Uninitialize(true);
429  AI::Uninitialize(true);
430  CheckConfig();
434 
435  /* We have loaded the config, so we may possibly save it. */
437 
438  /* restore saved music volume */
440 
443 
444 #if defined(ENABLE_NETWORK)
445  if (dedicated_host != NULL) {
448  }
450 #endif /* ENABLE_NETWORK */
451 
452  /* initialize the ingame console */
453  IConsoleInit();
454  InitializeGUI();
455  IConsoleCmdExec("exec scripts/autoexec.scr 0");
456 
457  /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
458  if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
459 
460 #ifdef ENABLE_NETWORK
461  if (_network_available && network_conn != NULL) {
462  const char *port = NULL;
463  const char *company = NULL;
464  uint16 rport = NETWORK_DEFAULT_PORT;
465  CompanyID join_as = COMPANY_NEW_COMPANY;
466 
467  ParseConnectionString(&company, &port, network_conn);
468 
469  if (company != NULL) {
470  join_as = (CompanyID)atoi(company);
471 
472  if (join_as != COMPANY_SPECTATOR) {
473  join_as--;
474  if (join_as >= MAX_COMPANIES) {
475  delete this;
476  return;
477  }
478  }
479  }
480  if (port != NULL) rport = atoi(port);
481 
482  LoadIntroGame();
483  _switch_mode = SM_NONE;
484  NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
485  }
486 #endif /* ENABLE_NETWORK */
487 
488  /* After the scan we're not used anymore. */
489  delete this;
490  }
491 };
492 
493 #if defined(UNIX) && !defined(__MORPHOS__)
494 extern void DedicatedFork();
495 #endif
496 
498 static const OptionData _options[] = {
499  GETOPT_SHORT_VALUE('I'),
500  GETOPT_SHORT_VALUE('S'),
501  GETOPT_SHORT_VALUE('M'),
502  GETOPT_SHORT_VALUE('m'),
503  GETOPT_SHORT_VALUE('s'),
504  GETOPT_SHORT_VALUE('v'),
505  GETOPT_SHORT_VALUE('b'),
506 #if defined(ENABLE_NETWORK)
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(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
513  GETOPT_SHORT_NOVAL('f'),
514 #endif
515 #endif /* ENABLE_NETWORK */
516  GETOPT_SHORT_VALUE('r'),
517  GETOPT_SHORT_VALUE('t'),
518  GETOPT_SHORT_OPTVAL('d'),
519  GETOPT_SHORT_NOVAL('e'),
520  GETOPT_SHORT_OPTVAL('g'),
521  GETOPT_SHORT_VALUE('G'),
522  GETOPT_SHORT_VALUE('c'),
523  GETOPT_SHORT_NOVAL('x'),
524  GETOPT_SHORT_VALUE('q'),
525  GETOPT_SHORT_NOVAL('h'),
526  GETOPT_END()
527 };
528 
535 int openttd_main(int argc, char *argv[])
536 {
537  char *musicdriver = NULL;
538  char *sounddriver = NULL;
539  char *videodriver = NULL;
540  char *blitter = NULL;
541  char *graphics_set = NULL;
542  char *sounds_set = NULL;
543  char *music_set = NULL;
544  Dimension resolution = {0, 0};
545  /* AfterNewGRFScan sets save_config to true after scanning completed. */
546  bool save_config = false;
547  AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
548 #if defined(ENABLE_NETWORK)
549  bool dedicated = false;
550  char *debuglog_conn = NULL;
551 
552  extern bool _dedicated_forks;
553  _dedicated_forks = false;
554 #endif /* ENABLE_NETWORK */
555 
556  _game_mode = GM_MENU;
558  _config_file = NULL;
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 #if defined(ENABLE_NETWORK)
574  case 'D':
575  free(musicdriver);
576  free(sounddriver);
577  free(videodriver);
578  free(blitter);
579  musicdriver = stredup("null");
580  sounddriver = stredup("null");
581  videodriver = stredup("dedicated");
582  blitter = stredup("null");
583  dedicated = true;
584  SetDebugString("net=6");
585  if (mgo.opt != NULL) {
586  /* Use the existing method for parsing (openttd -n).
587  * However, we do ignore the #company part. */
588  const char *temp = NULL;
589  const char *port = NULL;
590  ParseConnectionString(&temp, &port, mgo.opt);
591  if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
592  if (port != NULL) scanner->dedicated_port = atoi(port);
593  }
594  break;
595  case 'f': _dedicated_forks = true; break;
596  case 'n':
597  scanner->network_conn = mgo.opt; // optional IP parameter, NULL if unset
598  break;
599  case 'l':
600  debuglog_conn = mgo.opt;
601  break;
602  case 'p':
603  scanner->join_server_password = mgo.opt;
604  break;
605  case 'P':
606  scanner->join_company_password = mgo.opt;
607  break;
608 #endif /* ENABLE_NETWORK */
609  case 'r': ParseResolution(&resolution, mgo.opt); break;
610  case 't': scanner->startyear = atoi(mgo.opt); break;
611  case 'd': {
612 #if defined(WIN32)
613  CreateConsole();
614 #endif
615  if (mgo.opt != NULL) SetDebugString(mgo.opt);
616  break;
617  }
619  case 'g':
620  if (mgo.opt != NULL) {
621  strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
623  _file_to_saveload.mode = SL_LOAD;
624 
625  /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
626  const char *t = strrchr(_file_to_saveload.name, '.');
627  if (t != NULL) {
628  FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
629  if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
630  }
631 
632  break;
633  }
634 
636  /* Give a random map if no seed has been given */
637  if (scanner->generation_seed == GENERATE_NEW_SEED) {
638  scanner->generation_seed = InteractiveRandom();
639  }
640  break;
641  case 'q': {
642  DeterminePaths(argv[0]);
643  if (StrEmpty(mgo.opt)) {
644  ret = 1;
645  goto exit_noshutdown;
646  }
647 
648  char title[80];
649  title[0] = '\0';
650  FiosGetSavegameListCallback(SLD_LOAD_GAME, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
651 
654  if (res != SL_OK || _load_check_data.HasErrors()) {
655  fprintf(stderr, "Failed to open savegame\n");
656  if (_load_check_data.HasErrors()) {
657  char buf[256];
659  GetString(buf, _load_check_data.error, lastof(buf));
660  fprintf(stderr, "%s\n", buf);
661  }
662  goto exit_noshutdown;
663  }
664 
665  WriteSavegameInfo(title);
666 
667  goto exit_noshutdown;
668  }
669  case 'G': scanner->generation_seed = atoi(mgo.opt); break;
670  case 'c': free(_config_file); _config_file = stredup(mgo.opt); break;
671  case 'x': scanner->save_config = false; break;
672  case 'h':
673  i = -2; // Force printing of help.
674  break;
675  }
676  if (i == -2) break;
677  }
678 
679  if (i == -2 || mgo.numleft > 0) {
680  /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
681  * In all cases, print the help, and exit.
682  *
683  * The next two functions are needed to list the graphics sets. We can't do them earlier
684  * because then we cannot show it on the debug console as that hasn't been configured yet. */
685  DeterminePaths(argv[0]);
690  ShowHelp();
691 
692  goto exit_noshutdown;
693  }
694 
695 #if defined(WINCE) && defined(_DEBUG)
696  /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
697  SetDebugString("4");
698 #endif
699 
700  DeterminePaths(argv[0]);
702 
703 #if defined(ENABLE_NETWORK)
704  if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
705  if (_dedicated_forks && !dedicated) _dedicated_forks = false;
706 
707 #if defined(UNIX) && !defined(__MORPHOS__)
708  /* We must fork here, or we'll end up without some resources we need (like sockets) */
709  if (_dedicated_forks) DedicatedFork();
710 #endif
711 #endif
712 
713  LoadFromConfig(true);
714 
715  if (resolution.width != 0) _cur_resolution = resolution;
716 
717  /*
718  * The width and height must be at least 1 pixel and width times
719  * height times bytes per pixel must still fit within a 32 bits
720  * integer, even for 32 bpp video modes. This way all internal
721  * drawing routines work correctly.
722  */
723  _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX / 2);
724  _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
725 
726  /* Assume the cursor starts within the game as not all video drivers
727  * get an event that the cursor is within the window when it is opened.
728  * Saying the cursor is there makes no visible difference as it would
729  * just be out of the bounds of the window. */
730  _cursor.in_window = true;
731 
732  /* enumerate language files */
734 
735  /* Initialize the regular font for FreeType */
736  InitFreeType(false);
737 
738  /* This must be done early, since functions use the SetWindowDirty* calls */
740 
742  if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = stredup(BaseGraphics::ini_set);
743  if (!BaseGraphics::SetSet(graphics_set)) {
744  if (!StrEmpty(graphics_set)) {
745  BaseGraphics::SetSet(NULL);
746 
747  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
748  msg.SetDParamStr(0, graphics_set);
750  }
751  }
752  free(graphics_set);
753 
754  /* Initialize game palette */
755  GfxInitPalettes();
756 
757  DEBUG(misc, 1, "Loading blitter...");
758  if (blitter == NULL && _ini_blitter != NULL) blitter = stredup(_ini_blitter);
759  _blitter_autodetected = StrEmpty(blitter);
760  /* Activate the initial blitter.
761  * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
762  * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
763  * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
764  * - Use 8bpp blitter otherwise.
765  */
766  if (!_blitter_autodetected ||
767  (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
768  BlitterFactory::SelectBlitter("32bpp-anim") == NULL) {
769  if (BlitterFactory::SelectBlitter(blitter) == NULL) {
770  StrEmpty(blitter) ?
771  usererror("Failed to autoprobe blitter") :
772  usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
773  }
774  }
775  free(blitter);
776 
777  if (videodriver == NULL && _ini_videodriver != NULL) videodriver = stredup(_ini_videodriver);
779  free(videodriver);
780 
782 
783  /* Initialize the zoom level of the screen to normal */
784  _screen.zoom = ZOOM_LVL_NORMAL;
785 
786  NetworkStartUp(); // initialize network-core
787 
788 #if defined(ENABLE_NETWORK)
789  if (debuglog_conn != NULL && _network_available) {
790  const char *not_used = NULL;
791  const char *port = NULL;
792  uint16 rport;
793 
795 
796  ParseConnectionString(&not_used, &port, debuglog_conn);
797  if (port != NULL) rport = atoi(port);
798 
799  NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
800  }
801 #endif /* ENABLE_NETWORK */
802 
803  if (!HandleBootstrap()) {
804  ShutdownGame();
805 
806  goto exit_bootstrap;
807  }
808 
809  VideoDriver::GetInstance()->ClaimMousePointer();
810 
811  /* initialize screenshot formats */
813 
815  if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = stredup(BaseSounds::ini_set);
816  if (!BaseSounds::SetSet(sounds_set)) {
817  if (StrEmpty(sounds_set) || !BaseSounds::SetSet(NULL)) {
818  usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
819  } else {
820  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
821  msg.SetDParamStr(0, sounds_set);
823  }
824  }
825  free(sounds_set);
826 
828  if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = stredup(BaseMusic::ini_set);
829  if (!BaseMusic::SetSet(music_set)) {
830  if (StrEmpty(music_set) || !BaseMusic::SetSet(NULL)) {
831  usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
832  } else {
833  ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
834  msg.SetDParamStr(0, music_set);
836  }
837  }
838  free(music_set);
839 
840  if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = stredup(_ini_sounddriver);
842  free(sounddriver);
843 
844  if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = stredup(_ini_musicdriver);
846  free(musicdriver);
847 
848  /* Take our initial lock on whatever we might want to do! */
851 
852  GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
854 
855  LoadIntroGame(false);
856 
858 
859  /* ScanNewGRFFiles now has control over the scanner. */
860  ScanNewGRFFiles(scanner);
861  scanner = NULL;
862 
864 
865  WaitTillSaved();
866 
867  /* only save config if we have to */
868  if (save_config) {
869  SaveToConfig();
872  SaveToHighScore();
873  }
874 
875  /* Reset windowing system, stop drivers, free used memory, ... */
876  ShutdownGame();
877  goto exit_normal;
878 
879 exit_noshutdown:
880  /* These three are normally freed before bootstrap. */
881  free(graphics_set);
882  free(videodriver);
883  free(blitter);
884 
885 exit_bootstrap:
886  /* These are normally freed before exit, but after bootstrap. */
887  free(sounds_set);
888  free(music_set);
889  free(musicdriver);
890  free(sounddriver);
891 
892 exit_normal:
896 
901 
902  delete scanner;
903 
904 #ifdef ENABLE_NETWORK
905  extern FILE *_log_fd;
906  if (_log_fd != NULL) {
907  fclose(_log_fd);
908  }
909 #endif /* ENABLE_NETWORK */
910 
911  return ret;
912 }
913 
914 void HandleExitGameRequest()
915 {
916  if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
917  _exit_game = true;
919  DoExitSave();
920  _exit_game = true;
921  } else {
922  AskExitGame();
923  }
924 }
925 
926 static void MakeNewGameDone()
927 {
929 
930  /* In a dedicated server, the server does not play */
931  if (!VideoDriver::GetInstance()->HasGUI()) {
934  IConsoleCmdExec("exec scripts/game_start.scr 0");
935  return;
936  }
937 
938  /* Create a single company */
939  DoStartupNewCompany(false);
940 
943 
944  IConsoleCmdExec("exec scripts/game_start.scr 0");
945 
947 
949 
950 #ifdef ENABLE_NETWORK
951  /* We are the server, we start a new company (not dedicated),
952  * so set the default password *if* needed. */
955  }
956 #endif /* ENABLE_NETWORK */
957 
959 
960  CheckEngines();
961  CheckIndustries();
963 }
964 
965 static void MakeNewGame(bool from_heightmap, bool reset_settings)
966 {
967  _game_mode = GM_NORMAL;
968 
969  ResetGRFConfig(true);
970 
971  GenerateWorldSetCallback(&MakeNewGameDone);
973 }
974 
975 static void MakeNewEditorWorldDone()
976 {
978 }
979 
980 static void MakeNewEditorWorld()
981 {
982  _game_mode = GM_EDITOR;
983 
984  ResetGRFConfig(true);
985 
986  GenerateWorldSetCallback(&MakeNewEditorWorldDone);
988 }
989 
1000 bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
1001 {
1002  assert(mode == SL_LOAD || (lf == NULL && mode == SL_OLD_LOAD));
1003  GameMode ogm = _game_mode;
1004 
1005  _game_mode = newgm;
1006 
1007  switch (lf == NULL ? SaveOrLoad(filename, mode, subdir) : LoadWithFilter(lf)) {
1008  case SL_OK: return true;
1009 
1010  case SL_REINIT:
1011 #ifdef ENABLE_NETWORK
1012  if (_network_dedicated) {
1013  /*
1014  * We need to reinit a network map...
1015  * We can't simply load the intro game here as that game has many
1016  * special cases which make clients desync immediately. So we fall
1017  * back to just generating a new game with the current settings.
1018  */
1019  DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
1020  MakeNewGame(false, true);
1021  return false;
1022  }
1023  if (_network_server) {
1024  /* We can't load the intro game as server, so disconnect first. */
1026  }
1027 #endif /* ENABLE_NETWORK */
1028 
1029  switch (ogm) {
1030  default:
1031  case GM_MENU: LoadIntroGame(); break;
1032  case GM_EDITOR: MakeNewEditorWorld(); break;
1033  }
1034  return false;
1035 
1036  default:
1037  _game_mode = ogm;
1038  return false;
1039  }
1040 }
1041 
1042 void SwitchToMode(SwitchMode new_mode)
1043 {
1044 #ifdef ENABLE_NETWORK
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 #endif /* ENABLE_NETWORK */
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 #ifdef ENABLE_NETWORK
1085  if (_network_server) {
1087  }
1088 #endif /* ENABLE_NETWORK */
1089  MakeNewGame(false, new_mode == SM_NEWGAME);
1090  break;
1091 
1092  case SM_LOAD_GAME: { // Load game, Play Scenario
1093  ResetGRFConfig(true);
1095 
1096  if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
1098  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1099  } else {
1100  if (_saveload_mode == SLD_LOAD_SCENARIO) {
1101  /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1103  }
1104  /* Update the local company for a loaded game. It is either always
1105  * company #1 (eg 0) or in the case of a dedicated server a spectator */
1107  /* Execute the game-start script */
1108  IConsoleCmdExec("exec scripts/game_start.scr 0");
1109  /* Decrease pause counter (was increased from opening load dialog) */
1111 #ifdef ENABLE_NETWORK
1112  if (_network_server) {
1113  seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
1114  }
1115 #endif /* ENABLE_NETWORK */
1116  }
1117  break;
1118  }
1119 
1120  case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1121 #ifdef ENABLE_NETWORK
1122  if (_network_server) {
1123  seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
1124  }
1125 #endif /* ENABLE_NETWORK */
1126  MakeNewGame(true, true);
1127  break;
1128 
1129  case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1131 
1134  break;
1135 
1136  case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1137  if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
1140  /* Cancel the saveload pausing */
1142  } else {
1144  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1145  }
1146  break;
1147  }
1148 
1149  case SM_MENU: // Switch to game intro menu
1150  LoadIntroGame();
1151  if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
1152  ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1154  }
1155  break;
1156 
1157  case SM_SAVE_GAME: // Save game.
1158  /* Make network saved games on pause compatible to singleplayer */
1159  if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
1161  ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1162  } else {
1164  }
1165  break;
1166 
1167  case SM_SAVE_HEIGHTMAP: // Save heightmap.
1168  MakeHeightmapScreenshot(_file_to_saveload.name);
1170  break;
1171 
1172  case SM_GENRANDLAND: // Generate random land within scenario editor
1175  /* XXX: set date */
1177  break;
1178 
1179  default: NOT_REACHED();
1180  }
1181 }
1182 
1183 
1190 static void CheckCaches()
1191 {
1192  /* Return here so it is easy to add checks that are run
1193  * always to aid testing of caches. */
1194  if (_debug_desync_level <= 1) return;
1195 
1196  /* Check the town caches. */
1197  SmallVector<TownCache, 4> old_town_caches;
1198  Town *t;
1199  FOR_ALL_TOWNS(t) {
1200  MemCpyT(old_town_caches.Append(), &t->cache);
1201  }
1202 
1203  extern void RebuildTownCaches();
1206 
1207  uint i = 0;
1208  FOR_ALL_TOWNS(t) {
1209  if (MemCmpT(old_town_caches.Get(i), &t->cache) != 0) {
1210  DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
1211  }
1212  i++;
1213  }
1214 
1215  /* Check company infrastructure cache. */
1216  SmallVector<CompanyInfrastructure, 4> old_infrastructure;
1217  Company *c;
1218  FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
1219 
1220  extern void AfterLoadCompanyStats();
1222 
1223  i = 0;
1224  FOR_ALL_COMPANIES(c) {
1225  if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
1226  DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
1227  }
1228  i++;
1229  }
1230 
1231  /* Strict checking of the road stop cache entries */
1232  const RoadStop *rs;
1233  FOR_ALL_ROADSTOPS(rs) {
1234  if (IsStandardRoadStopTile(rs->xy)) continue;
1235 
1236  assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
1239  }
1240 
1241  Vehicle *v;
1242  FOR_ALL_VEHICLES(v) {
1243  extern void FillNewGRFVehicleCache(const Vehicle *v);
1244  if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1245 
1246  uint length = 0;
1247  for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
1248 
1249  NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1250  VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1251  GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
1252  TrainCache *tra_cache = CallocT<TrainCache>(length);
1253 
1254  length = 0;
1255  for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1257  grf_cache[length] = u->grf_cache;
1258  veh_cache[length] = u->vcache;
1259  switch (u->type) {
1260  case VEH_TRAIN:
1261  gro_cache[length] = Train::From(u)->gcache;
1262  tra_cache[length] = Train::From(u)->tcache;
1263  break;
1264  case VEH_ROAD:
1265  gro_cache[length] = RoadVehicle::From(u)->gcache;
1266  break;
1267  default:
1268  break;
1269  }
1270  length++;
1271  }
1272 
1273  switch (v->type) {
1274  case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
1277  case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
1278  default: break;
1279  }
1280 
1281  length = 0;
1282  for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1284  if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1285  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);
1286  }
1287  if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1288  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);
1289  }
1290  switch (u->type) {
1291  case VEH_TRAIN:
1292  if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1293  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);
1294  }
1295  if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1296  DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1297  }
1298  break;
1299  case VEH_ROAD:
1300  if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1301  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);
1302  }
1303  break;
1304  default:
1305  break;
1306  }
1307  length++;
1308  }
1309 
1310  free(grf_cache);
1311  free(veh_cache);
1312  free(gro_cache);
1313  free(tra_cache);
1314  }
1315 
1316  /* Check whether the caches are still valid */
1317  FOR_ALL_VEHICLES(v) {
1318  byte buff[sizeof(VehicleCargoList)];
1319  memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1320  v->cargo.InvalidateCache();
1321  assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1322  }
1323 
1324  Station *st;
1325  FOR_ALL_STATIONS(st) {
1326  for (CargoID c = 0; c < NUM_CARGO; c++) {
1327  byte buff[sizeof(StationCargoList)];
1328  memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
1329  st->goods[c].cargo.InvalidateCache();
1330  assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
1331  }
1332  }
1333 }
1334 
1341 {
1342  /* don't execute the state loop during pause */
1343  if (_pause_mode != PM_UNPAUSED) {
1345 #ifndef DEBUG_DUMP_COMMANDS
1346  Game::GameLoop();
1347 #endif
1349  return;
1350  }
1351  if (HasModalProgress()) return;
1352 
1354 
1355  if (_game_mode == GM_EDITOR) {
1357  RunTileLoop();
1358  CallVehicleTicks();
1359  CallLandscapeTick();
1362 
1364  NewsLoop();
1365  } else {
1366  if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
1367  /* Save the desync savegame if needed. */
1368  char name[MAX_PATH];
1369  seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
1370  SaveOrLoad(name, SL_SAVE, AUTOSAVE_DIR, false);
1371  }
1372 
1373  CheckCaches();
1374 
1375  /* All these actions has to be done from OWNER_NONE
1376  * for multiplayer compatibility */
1377  Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1378 
1381  IncreaseDate();
1382  RunTileLoop();
1383  CallVehicleTicks();
1384  CallLandscapeTick();
1386 
1387 #ifndef DEBUG_DUMP_COMMANDS
1388  AI::GameLoop();
1389  Game::GameLoop();
1390 #endif
1392 
1394  NewsLoop();
1395  cur_company.Restore();
1396  }
1397 
1398  assert(IsLocalCompany());
1399 }
1400 
1405 static void DoAutosave()
1406 {
1407  char buf[MAX_PATH];
1408 
1409 #if defined(PSP)
1410  /* Autosaving in networking is too time expensive for the PSP */
1411  if (_networking) return;
1412 #endif /* PSP */
1413 
1415  GenerateDefaultSaveName(buf, lastof(buf));
1416  strecat(buf, ".sav", lastof(buf));
1417  } else {
1418  static int _autosave_ctr = 0;
1419 
1420  /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1421  seprintf(buf, lastof(buf), "autosave%d.sav", _autosave_ctr);
1422 
1423  if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
1424  }
1425 
1426  DEBUG(sl, 2, "Autosaving to '%s'", buf);
1427  if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
1428  ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
1429  }
1430 }
1431 
1432 void GameLoop()
1433 {
1434  if (_game_mode == GM_BOOTSTRAP) {
1435 #ifdef ENABLE_NETWORK
1436  /* Check for UDP stuff */
1438 #endif
1439  InputLoop();
1440  return;
1441  }
1442 
1444 
1445  /* autosave game? */
1446  if (_do_autosave) {
1447  DoAutosave();
1448  _do_autosave = false;
1450  }
1451 
1452  /* switch game mode? */
1453  if (_switch_mode != SM_NONE && !HasModalProgress()) {
1454  SwitchToMode(_switch_mode);
1455  _switch_mode = SM_NONE;
1456  }
1457 
1458  IncreaseSpriteLRU();
1459  InteractiveRandom();
1460 
1461  extern int _caret_timer;
1462  _caret_timer += 3;
1463  CursorTick();
1464 
1465 #ifdef ENABLE_NETWORK
1466  /* Check for UDP stuff */
1468 
1469  if (_networking && !HasModalProgress()) {
1470  /* Multiplayer */
1471  NetworkGameLoop();
1472  } else {
1473  if (_network_reconnect > 0 && --_network_reconnect == 0) {
1474  /* This means that we want to reconnect to the last host
1475  * We do this here, because it means that the network is really closed */
1477  }
1478  /* Singleplayer */
1479  StateGameLoop();
1480  }
1481 
1482  /* Check chat messages roughly once a second. */
1483  static uint check_message = 0;
1484  if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
1485  check_message = 0;
1487  }
1488 #else
1489  StateGameLoop();
1490 #endif /* ENABLE_NETWORK */
1491 
1492  if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1493 
1494  if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
1495 
1496  InputLoop();
1497 
1499  MusicLoop();
1500 }