# openttd.cpp

Go to the documentation of this file.

    00001 /* $Id: openttd.cpp 15495 2009-02-14 23:17:32Z yexo $ */
    00002
    00005 #include "stdafx.h"
    00006
    00007 #define VARDEF
    00008 #include "variables.h"
    00009 #undef VARDEF
    00010
    00011 #include "openttd.h"
    00012
    00013 #include "blitter/factory.hpp"
    00014 #include "sound/sound_driver.hpp"
    00015 #include "music/music_driver.hpp"
    00016 #include "video/video_driver.hpp"
    00017
    00018 #include "fontcache.h"
    00019 #include "gfxinit.h"
    00020 #include "gui.h"
    00021 #include "mixer.h"
    00022 #include "sound_func.h"
    00023 #include "window_func.h"
    00024
    00025 #include "saveload/saveload.h"
    00026 #include "landscape.h"
    00027 #include "company_func.h"
    00028 #include "command_func.h"
    00029 #include "news_func.h"
    00030 #include "fileio_func.h"
    00031 #include "fios.h"
    00032 #include "aircraft.h"
    00033 #include "console_func.h"
    00034 #include "screenshot.h"
    00035 #include "network/network.h"
    00036 #include "network/network_func.h"
    00037 #include "signs_base.h"
    00038 #include "ai/ai.hpp"
    00039 #include "ai/ai_config.hpp"
    00040 #include "settings_func.h"
    00041 #include "genworld.h"
    00042 #include "group.h"
    00043 #include "strings_func.h"
    00044 #include "date_func.h"
    00045 #include "vehicle_func.h"
    00046 #include "gamelog.h"
    00047 #include "cheat_type.h"
    00048 #include "animated_tile_func.h"
    00049 #include "functions.h"
    00050 #include "elrail_func.h"
    00051 #include "rev.h"
    00052 #include "highscore.h"
    00053
    00054 #include "newgrf_commons.h"
    00055
    00056 #include "town.h"
    00057 #include "industry.h"
    00058
    00059 #include <stdarg.h>
    00060
    00061 #include "table/strings.h"
    00062
    00063 StringID _switch_mode_errorstr;
    00064
    00065 void CallLandscapeTick();
    00066 void IncreaseDate();
    00067 void DoPaletteAnimations();
    00068 void MusicLoop();
    00069 void ResetMusic();
    00070 void ProcessAsyncSaveFinish();
    00071 void CallWindowTickEvent();
    00072
    00073 extern void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
    00074 extern Company *DoStartupNewCompany(bool is_ai);
    00075 extern void ShowOSErrorBox(const char *buf, bool system);
    00076 extern void InitializeRailGUI();
    00077
    00083 void CDECL usererror(const char *s, ...)
    00084 {
    00085   va_list va;
    00086   char buf[512];
    00087
    00088   va_start(va, s);
    00089   vsnprintf(buf, lengthof(buf), s, va);
    00090   va_end(va);
    00091
    00092   ShowOSErrorBox(buf, false);
    00093   if (_video_driver != NULL) _video_driver->Stop();
    00094
    00095   exit(1);
    00096 }
    00097
    00103 void CDECL error(const char *s, ...)
    00104 {
    00105   va_list va;
    00106   char buf[512];
    00107
    00108   va_start(va, s);
    00109   vsnprintf(buf, lengthof(buf), s, va);
    00110   va_end(va);
    00111
    00112   ShowOSErrorBox(buf, true);
    00113   if (_video_driver != NULL) _video_driver->Stop();
    00114
    00115   assert(0);
    00116   exit(1);
    00117 }
    00118
    00123 void CDECL ShowInfoF(const char *str, ...)
    00124 {
    00125   va_list va;
    00126   char buf[1024];
    00127   va_start(va, str);
    00128   vsnprintf(buf, lengthof(buf), str, va);
    00129   va_end(va);
    00130   ShowInfo(buf);
    00131 }
    00132
    00136 static void ShowHelp()
    00137 {
    00138   char buf[8192];
    00139   char *p = buf;
    00140
    00141   p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
    00142   p = strecpy(p,
    00143     "\n"
    00144     "\n"
    00145     "Command line options:\n"
    00146     "  -v drv              = Set video driver (see below)\n"
    00147     "  -s drv              = Set sound driver (see below) (param bufsize,hz)\n"
    00148     "  -m drv              = Set music driver (see below)\n"
    00149     "  -b drv              = Set the blitter to use (see below)\n"
    00150     "  -a ai               = Force use of specific AI (see below)\n"
    00151     "  -r res              = Set resolution (for instance 800x600)\n"
    00152     "  -h                  = Display this help text\n"
    00153     "  -t year             = Set starting year\n"
    00154     "  -d [[fac=]lvl[,...]]= Debug mode\n"
    00155     "  -e                  = Start Editor\n"
    00156     "  -g [savegame]       = Start new/save game immediately\n"
    00157     "  -G seed             = Set random seed\n"
    00158 #if defined(ENABLE_NETWORK)
    00159     "  -n [ip:port#company]= Start networkgame\n"
    00160     "  -D [ip][:port]      = Start dedicated server\n"
    00161     "  -l ip[:port]        = Redirect DEBUG()\n"
    00162 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
    00163     "  -f                  = Fork into the background (dedicated only)\n"
    00164 #endif
    00165 #endif /* ENABLE_NETWORK */
    00166     "  -i palette          = Force to use the DOS (0) or Windows (1) palette\n"
    00167     "                          (defines default setting when adding newgrfs)\n"
    00168     "                        Default value (2) lets OpenTTD use the palette\n"
    00169     "                          specified in graphics set file (see below)\n"
    00170     "  -I graphics_set     = Force the graphics set (see below)\n"
    00171     "  -c config_file      = Use 'config_file' instead of 'openttd.cfg'\n"
    00172     "  -x                  = Do not automatically save to config file on exit\n"
    00173     "\n",
    00174     lastof(buf)
    00175   );
    00176
    00177   /* List the graphics packs */
    00178   p = GetGraphicsSetsList(p, lastof(buf));
    00179
    00180   /* List the drivers */
    00181   p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
    00182
    00183   /* List the blitters */
    00184   p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
    00185
    00186   /* We need to initialize the AI, so it finds the AIs */
    00187   AI::Initialize();
    00188   p = AI::GetConsoleList(p, lastof(buf));
    00189   AI::Uninitialize(true);
    00190
    00191   /* ShowInfo put output to stderr, but version information should go
    00192    * to stdout; this is the only exception */
    00193 #if !defined(WIN32) && !defined(WIN64)
    00194   printf("%s\n", buf);
    00195 #else
    00196   ShowInfo(buf);
    00197 #endif
    00198 }
    00199
    00200
    00201 struct MyGetOptData {
    00202   char *opt;
    00203   int numleft;
    00204   char **argv;
    00205   const char *options;
    00206   const char *cont;
    00207
    00208   MyGetOptData(int argc, char **argv, const char *options)
    00209   {
    00210     opt = NULL;
    00211     numleft = argc;
    00212     this->argv = argv;
    00213     this->options = options;
    00214     cont = NULL;
    00215   }
    00216 };
    00217
    00218 static int MyGetOpt(MyGetOptData *md)
    00219 {
    00220   const char *s,*r,*t;
    00221
    00222   s = md->cont;
    00223   if (s != NULL)
    00224     goto md_continue_here;
    00225
    00226   for (;;) {
    00227     if (--md->numleft < 0) return -1;
    00228
    00229     s = *md->argv++;
    00230     if (*s == '-') {
    00231 md_continue_here:;
    00232       s++;
    00233       if (*s != 0) {
    00234         /* Found argument, try to locate it in options. */
    00235         if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
    00236           /* ERROR! */
    00237           return -2;
    00238         }
    00239         if (r[1] == ':') {
    00240           /* Item wants an argument. Check if the argument follows, or if it comes as a separate arg. */
    00241           if (!*(t = s + 1)) {
    00242             /* It comes as a separate arg. Check if out of args? */
    00243             if (--md->numleft < 0 || *(t = *md->argv) == '-') {
    00244               /* Check if item is optional? */
    00245               if (r[2] != ':')
    00246                 return -2;
    00247               md->numleft++;
    00248               t = NULL;
    00249             } else {
    00250               md->argv++;
    00251             }
    00252           }
    00253           md->opt = (char*)t;
    00254           md->cont = NULL;
    00255           return *s;
    00256         }
    00257         md->opt = NULL;
    00258         md->cont = s;
    00259         return *s;
    00260       }
    00261     } else {
    00262       /* This is currently not supported. */
    00263       return -2;
    00264     }
    00265   }
    00266 }
    00267
    00274 static void ParseResolution(Dimension *res, const char *s)
    00275 {
    00276   const char *t = strchr(s, 'x');
    00277   if (t == NULL) {
    00278     ShowInfoF("Invalid resolution '%s'", s);
    00279     return;
    00280   }
    00281
    00282   res->width  = max(strtoul(s, NULL, 0), 64UL);
    00283   res->height = max(strtoul(t + 1, NULL, 0), 64UL);
    00284 }
    00285
    00286 static void InitializeDynamicVariables()
    00287 {
    00288   /* Dynamic stuff needs to be initialized somewhere... */
    00289   _industry_mngr.ResetMapping();
    00290   _industile_mngr.ResetMapping();
    00291   _Company_pool.AddBlockToPool();
    00292 }
    00293
    00294
    00298 static void ShutdownGame()
    00299 {
    00300   /* stop the AI */
    00301   AI::Uninitialize(false);
    00302
    00303   IConsoleFree();
    00304
    00305   if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
    00306
    00307   DriverFactoryBase::ShutdownDrivers();
    00308
    00309   UnInitWindowSystem();
    00310
    00311   /* Uninitialize airport state machines */
    00312   UnInitializeAirports();
    00313
    00314   /* Uninitialize variables that are allocated dynamically */
    00315   GamelogReset();
    00316   _Town_pool.CleanPool();
    00317   _Industry_pool.CleanPool();
    00318   _Station_pool.CleanPool();
    00319   _Vehicle_pool.CleanPool();
    00320   _Sign_pool.CleanPool();
    00321   _Order_pool.CleanPool();
    00322   _Group_pool.CleanPool();
    00323   _CargoPacket_pool.CleanPool();
    00324   _Engine_pool.CleanPool();
    00325   _Company_pool.CleanPool();
    00326
    00327   free(_config_file);
    00328
    00329   /* Close all and any open filehandles */
    00330   FioCloseAll();
    00331 }
    00332
    00333 static void LoadIntroGame()
    00334 {
    00335   _game_mode = GM_MENU;
    00336
    00337   ResetGRFConfig(false);
    00338
    00339   /* Setup main window */
    00340   ResetWindowSystem();
    00341   SetupColoursAndInitialWindow();
    00342
    00343   /* Load the default opening screen savegame */
    00344   if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
    00345     GenerateWorld(GW_EMPTY, 64, 64); // if failed loading, make empty world.
    00346     WaitTillGeneratedWorld();
    00347     SetLocalCompany(COMPANY_SPECTATOR);
    00348   } else {
    00349     SetLocalCompany(COMPANY_FIRST);
    00350   }
    00351
    00352   _pause_game = 0;
    00353   _cursor.fix_at = false;
    00354
    00355   CheckForMissingGlyphsInLoadedLanguagePack();
    00356
    00357   /* Play main theme */
    00358   if (_music_driver->IsSongPlaying()) ResetMusic();
    00359 }
    00360
    00361 void MakeNewgameSettingsLive()
    00362 {
    00363   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
    00364     if (_settings_game.ai_config[c] != NULL) {
    00365       delete _settings_game.ai_config[c];
    00366     }
    00367   }
    00368
    00369   _settings_game = _settings_newgame;
    00370
    00371   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
    00372     _settings_game.ai_config[c] = NULL;
    00373     if (_settings_newgame.ai_config[c] != NULL) {
    00374       _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
    00375     }
    00376   }
    00377 }
    00378
    00379 byte _savegame_sort_order;
    00380 #if defined(UNIX) && !defined(__MORPHOS__)
    00381 extern void DedicatedFork();
    00382 #endif
    00383
    00384 int ttd_main(int argc, char *argv[])
    00385 {
    00386   int i;
    00387   const char *optformat;
    00388   char *musicdriver = NULL;
    00389   char *sounddriver = NULL;
    00390   char *videodriver = NULL;
    00391   char *blitter = NULL;
    00392   char *graphics_set = NULL;
    00393   Dimension resolution = {0, 0};
    00394   Year startyear = INVALID_YEAR;
    00395   uint generation_seed = GENERATE_NEW_SEED;
    00396   bool save_config = true;
    00397 #if defined(ENABLE_NETWORK)
    00398   bool dedicated = false;
    00399   bool network   = false;
    00400   char *network_conn = NULL;
    00401   char *debuglog_conn = NULL;
    00402   char *dedicated_host = NULL;
    00403   uint16 dedicated_port = 0;
    00404 #endif /* ENABLE_NETWORK */
    00405
    00406   _game_mode = GM_MENU;
    00407   _switch_mode = SM_MENU;
    00408   _switch_mode_errorstr = INVALID_STRING_ID;
    00409   _dedicated_forks = false;
    00410   _config_file = NULL;
    00411
    00412   /* The last param of the following function means this:
    00413    *   a letter means: it accepts that param (e.g.: -h)
    00414    *   a ':' behind it means: it need a param (e.g.: -m<driver>)
    00415    *   a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
    00416   optformat = "m:s:v:b:hD::n::ei::I:t:d::r:g::G:c:xl:"
    00417 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
    00418     "f"
    00419 #endif
    00420   ;
    00421
    00422   MyGetOptData mgo(argc - 1, argv + 1, optformat);
    00423
    00424   while ((i = MyGetOpt(&mgo)) != -1) {
    00425     switch (i) {
    00426     case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
    00427     case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
    00428     case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
    00429     case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
    00430     case 'b': free(blitter); blitter = strdup(mgo.opt); break;
    00431 #if defined(ENABLE_NETWORK)
    00432     case 'D':
    00433       free(musicdriver);
    00434       free(sounddriver);
    00435       free(videodriver);
    00436       free(blitter);
    00437       musicdriver = strdup("null");
    00438       sounddriver = strdup("null");
    00439       videodriver = strdup("dedicated");
    00440       blitter = strdup("null");
    00441       dedicated = true;
    00442       if (mgo.opt != NULL) {
    00443         /* Use the existing method for parsing (openttd -n).
    00444          * However, we do ignore the #company part. */
    00445         const char *temp = NULL;
    00446         const char *port = NULL;
    00447         ParseConnectionString(&temp, &port, mgo.opt);
    00448         if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
    00449         if (port != NULL) dedicated_port = atoi(port);
    00450       }
    00451       break;
    00452     case 'f': _dedicated_forks = true; break;
    00453     case 'n':
    00454       network = true;
    00455       network_conn = mgo.opt; // optional IP parameter, NULL if unset
    00456       break;
    00457     case 'l':
    00458       debuglog_conn = mgo.opt;
    00459       break;
    00460 #endif /* ENABLE_NETWORK */
    00461     case 'r': ParseResolution(&resolution, mgo.opt); break;
    00462     case 't': startyear = atoi(mgo.opt); break;
    00463     case 'd': {
    00464 #if defined(WIN32)
    00465         CreateConsole();
    00466 #endif
    00467         if (mgo.opt != NULL) SetDebugString(mgo.opt);
    00468       } break;
    00469     case 'e': _switch_mode = SM_EDITOR; break;
    00470     case 'i':
    00471       /* there is an argument, it is not empty, and it is exactly 1 char long */
    00472       if (!StrEmpty(mgo.opt) && mgo.opt[1] == '\0') {
    00473         _use_palette = (PaletteType)(mgo.opt[0] - '0');
    00474         if (_use_palette <= MAX_PAL) break;
    00475       }
    00476       usererror("Valid value for '-i' is 0, 1 or 2");
    00477     case 'g':
    00478       if (mgo.opt != NULL) {
    00479         strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
    00480         _switch_mode = SM_LOAD;
    00481         _file_to_saveload.mode = SL_LOAD;
    00482
    00483         /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
    00484         const char *t = strrchr(_file_to_saveload.name, '.');
    00485         if (t != NULL) {
    00486           FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
    00487           if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
    00488         }
    00489
    00490         break;
    00491       }
    00492
    00493       _switch_mode = SM_NEWGAME;
    00494       /* Give a random map if no seed has been given */
    00495       if (generation_seed == GENERATE_NEW_SEED) {
    00496         generation_seed = InteractiveRandom();
    00497       }
    00498       break;
    00499     case 'G': generation_seed = atoi(mgo.opt); break;
    00500     case 'c': _config_file = strdup(mgo.opt); break;
    00501     case 'x': save_config = false; break;
    00502     case -2:
    00503     case 'h':
    00504       /* The next two functions are needed to list the graphics sets.
    00505        * We can't do them earlier because then we can't show it on
    00506        * the debug console as that hasn't been configured yet. */
    00507       DeterminePaths(argv[0]);
    00508       FindGraphicsSets();
    00509       ShowHelp();
    00510       return 0;
    00511     }
    00512   }
    00513
    00514 #if defined(WINCE) && defined(_DEBUG)
    00515   /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
    00516   SetDebugString("4");
    00517 #endif
    00518
    00519   DeterminePaths(argv[0]);
    00520   FindGraphicsSets();
    00521
    00522 #if defined(UNIX) && !defined(__MORPHOS__)
    00523   /* We must fork here, or we'll end up without some resources we need (like sockets) */
    00524   if (_dedicated_forks)
    00525     DedicatedFork();
    00526 #endif
    00527
    00528   AI::Initialize();
    00529   LoadFromConfig();
    00530   AI::Uninitialize(true);
    00531   CheckConfig();
    00532   LoadFromHighScore();
    00533
    00534   if (resolution.width != 0) { _cur_resolution = resolution; }
    00535   if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
    00536   if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
    00537
    00538   /* The width and height must be at least 1 pixel, this
    00539    * way all internal drawing routines work correctly. */
    00540   if (_cur_resolution.width  <= 0) _cur_resolution.width  = 1;
    00541   if (_cur_resolution.height <= 0) _cur_resolution.height = 1;
    00542
    00543 #if defined(ENABLE_NETWORK)
    00544   if (dedicated_host) snprintf(_settings_client.network.server_bind_ip, sizeof(_settings_client.network.server_bind_ip), "%s", dedicated_host);
    00545   if (dedicated_port) _settings_client.network.server_port = dedicated_port;
    00546   if (_dedicated_forks && !dedicated) _dedicated_forks = false;
    00547 #endif /* ENABLE_NETWORK */
    00548
    00549   /* enumerate language files */
    00550   InitializeLanguagePacks();
    00551
    00552   /* initialize screenshot formats */
    00553   InitializeScreenshotFormats();
    00554
    00555   /* initialize airport state machines */
    00556   InitializeAirports();
    00557
    00558   /* initialize all variables that are allocated dynamically */
    00559   InitializeDynamicVariables();
    00560
    00561   /* Sample catalogue */
    00562   DEBUG(misc, 1, "Loading sound effects...");
    00563   MxInitialize(11025);
    00564   SoundInitialize("sample.cat");
    00565
    00566   /* Initialize FreeType */
    00567   InitFreeType();
    00568
    00569   /* This must be done early, since functions use the InvalidateWindow* calls */
    00570   InitWindowSystem();
    00571
    00572   if (graphics_set == NULL) graphics_set = _ini_graphics_set;
    00573   if (!SetGraphicsSet(graphics_set)) {
    00574     StrEmpty(graphics_set) ?
    00575       usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD.") :
    00576       usererror("Failed to select requested graphics set '%s'", graphics_set);
    00577   }
    00578
    00579   /* Initialize game palette */
    00580   GfxInitPalettes();
    00581
    00582   DEBUG(misc, 1, "Loading blitter...");
    00583   if (blitter == NULL) blitter = _ini_blitter;
    00584   if (BlitterFactoryBase::SelectBlitter(blitter) == NULL)
    00585     StrEmpty(blitter) ?
    00586       usererror("Failed to autoprobe blitter") :
    00587       usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
    00588
    00589   DEBUG(driver, 1, "Loading drivers...");
    00590
    00591   if (sounddriver == NULL) sounddriver = _ini_sounddriver;
    00592   _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
    00593   if (_sound_driver == NULL) {
    00594     StrEmpty(sounddriver) ?
    00595       usererror("Failed to autoprobe sound driver") :
    00596       usererror("Failed to select requested sound driver '%s'", sounddriver);
    00597   }
    00598
    00599   if (musicdriver == NULL) musicdriver = _ini_musicdriver;
    00600   _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
    00601   if (_music_driver == NULL) {
    00602     StrEmpty(musicdriver) ?
    00603       usererror("Failed to autoprobe music driver") :
    00604       usererror("Failed to select requested music driver '%s'", musicdriver);
    00605   }
    00606
    00607   if (videodriver == NULL) videodriver = _ini_videodriver;
    00608   _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
    00609   if (_video_driver == NULL) {
    00610     StrEmpty(videodriver) ?
    00611       usererror("Failed to autoprobe video driver") :
    00612       usererror("Failed to select requested video driver '%s'", videodriver);
    00613   }
    00614
    00615   _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
    00616   /* Initialize the zoom level of the screen to normal */
    00617   _screen.zoom = ZOOM_LVL_NORMAL;
    00618
    00619   /* restore saved music volume */
    00620   _music_driver->SetVolume(msf.music_vol);
    00621
    00622   NetworkStartUp(); // initialize network-core
    00623
    00624 #if defined(ENABLE_NETWORK)
    00625   if (debuglog_conn != NULL && _network_available) {
    00626     const char *not_used = NULL;
    00627     const char *port = NULL;
    00628     uint16 rport;
    00629
    00630     rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
    00631
    00632     ParseConnectionString(&not_used, &port, debuglog_conn);
    00633     if (port != NULL) rport = atoi(port);
    00634
    00635     NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
    00636   }
    00637 #endif /* ENABLE_NETWORK */
    00638
    00639   ScanNewGRFFiles();
    00640
    00641   ResetGRFConfig(false);
    00642
    00643   /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
    00644   if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
    00645
    00646   /* initialize the ingame console */
    00647   IConsoleInit();
    00648   _cursor.in_window = true;
    00649   InitializeGUI();
    00650   IConsoleCmdExec("exec scripts/autoexec.scr 0");
    00651
    00652   GenerateWorld(GW_EMPTY, 64, 64); // Make the viewport initialization happy
    00653   WaitTillGeneratedWorld();
    00654
    00655   CheckForMissingGlyphsInLoadedLanguagePack();
    00656
    00657 #ifdef ENABLE_NETWORK
    00658   if (network && _network_available) {
    00659     if (network_conn != NULL) {
    00660       const char *port = NULL;
    00661       const char *company = NULL;
    00662       uint16 rport;
    00663
    00664       rport = NETWORK_DEFAULT_PORT;
    00665       _network_playas = COMPANY_NEW_COMPANY;
    00666
    00667       ParseConnectionString(&company, &port, network_conn);
    00668
    00669       if (company != NULL) {
    00670         _network_playas = (CompanyID)atoi(company);
    00671
    00672         if (_network_playas != COMPANY_SPECTATOR) {
    00673           _network_playas--;
    00674           if (_network_playas >= MAX_COMPANIES) return false;
    00675         }
    00676       }
    00677       if (port != NULL) rport = atoi(port);
    00678
    00679       LoadIntroGame();
    00680       _switch_mode = SM_NONE;
    00681       NetworkClientConnectGame(NetworkAddress(network_conn, rport));
    00682     }
    00683   }
    00684 #endif /* ENABLE_NETWORK */
    00685
    00686   _video_driver->MainLoop();
    00687
    00688   WaitTillSaved();
    00689
    00690   /* only save config if we have to */
    00691   if (save_config) {
    00692     SaveToConfig();
    00693     SaveToHighScore();
    00694   }
    00695
    00696   /* Reset windowing system, stop drivers, free used memory, ... */
    00697   ShutdownGame();
    00698
    00699   return 0;
    00700 }
    00701
    00702 void HandleExitGameRequest()
    00703 {
    00704   if (_game_mode == GM_MENU) { // do not ask to quit on the main screen
    00705     _exit_game = true;
    00706   } else if (_settings_client.gui.autosave_on_exit) {
    00707     DoExitSave();
    00708     _exit_game = true;
    00709   } else {
    00710     AskExitGame();
    00711   }
    00712 }
    00713
    00714 static void ShowScreenshotResult(bool b)
    00715 {
    00716   if (b) {
    00717     SetDParamStr(0, _screenshot_name);
    00718     ShowErrorMessage(INVALID_STRING_ID, STR_031B_SCREENSHOT_SUCCESSFULLY, 0, 0);
    00719   } else {
    00720     ShowErrorMessage(INVALID_STRING_ID, STR_031C_SCREENSHOT_FAILED, 0, 0);
    00721   }
    00722
    00723 }
    00724
    00725 static void MakeNewGameDone()
    00726 {
    00727   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
    00728
    00729   /* In a dedicated server, the server does not play */
    00730   if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0) {
    00731     SetLocalCompany(COMPANY_SPECTATOR);
    00732     IConsoleCmdExec("exec scripts/game_start.scr 0");
    00733     return;
    00734   }
    00735
    00736   /* Create a single company */
    00737   DoStartupNewCompany(false);
    00738
    00739   IConsoleCmdExec("exec scripts/game_start.scr 0");
    00740
    00741   SetLocalCompany(COMPANY_FIRST);
    00742   _current_company = _local_company;
    00743   DoCommandP(0, (_settings_client.gui.autorenew << 15 ) | (_settings_client.gui.autorenew_months << 16) | 4, _settings_client.gui.autorenew_money, CMD_SET_AUTOREPLACE);
    00744
    00745   InitializeRailGUI();
    00746
    00747 #ifdef ENABLE_NETWORK
    00748   /* We are the server, we start a new company (not dedicated),
    00749    * so set the default password *if* needed. */
    00750   if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
    00751     char *password = _settings_client.network.default_company_pass;
    00752     NetworkChangeCompanyPassword(1, &password);
    00753   }
    00754 #endif /* ENABLE_NETWORK */
    00755
    00756   MarkWholeScreenDirty();
    00757 }
    00758
    00759 static void MakeNewGame(bool from_heightmap)
    00760 {
    00761   _game_mode = GM_NORMAL;
    00762
    00763   ResetGRFConfig(true);
    00764   _house_mngr.ResetMapping();
    00765   _industile_mngr.ResetMapping();
    00766   _industry_mngr.ResetMapping();
    00767
    00768   GenerateWorldSetCallback(&MakeNewGameDone);
    00769   GenerateWorld(from_heightmap ? GW_HEIGHTMAP : GW_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
    00770 }
    00771
    00772 static void MakeNewEditorWorldDone()
    00773 {
    00774   SetLocalCompany(OWNER_NONE);
    00775 }
    00776
    00777 static void MakeNewEditorWorld()
    00778 {
    00779   _game_mode = GM_EDITOR;
    00780
    00781   ResetGRFConfig(true);
    00782
    00783   GenerateWorldSetCallback(&MakeNewEditorWorldDone);
    00784   GenerateWorld(GW_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
    00785 }
    00786
    00787 void StartupCompanies();
    00788 void StartupDisasters();
    00789 extern void StartupEconomy();
    00790
    00796 static void StartScenario()
    00797 {
    00798   _game_mode = GM_NORMAL;
    00799
    00800   /* invalid type */
    00801   if (_file_to_saveload.mode == SL_INVALID) {
    00802     DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
    00803     SetDParamStr(0, GetSaveLoadErrorString());
    00804     ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
    00805     _game_mode = GM_MENU;
    00806     return;
    00807   }
    00808
    00809   /* Reinitialize windows */
    00810   ResetWindowSystem();
    00811
    00812   SetupColoursAndInitialWindow();
    00813
    00814   ResetGRFConfig(true);
    00815
    00816   /* Load game */
    00817   if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, SCENARIO_DIR) != SL_OK) {
    00818     LoadIntroGame();
    00819     SetDParamStr(0, GetSaveLoadErrorString());
    00820     ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
    00821   }
    00822
    00823   _settings_game.difficulty = _settings_newgame.difficulty;
    00824
    00825   /* Inititalize data */
    00826   StartupEconomy();
    00827   StartupCompanies();
    00828   StartupEngines();
    00829   StartupDisasters();
    00830
    00831   SetLocalCompany(COMPANY_FIRST);
    00832   _current_company = _local_company;
    00833   DoCommandP(0, (_settings_client.gui.autorenew << 15 ) | (_settings_client.gui.autorenew_months << 16) | 4, _settings_client.gui.autorenew_money, CMD_SET_AUTOREPLACE);
    00834
    00835   MarkWholeScreenDirty();
    00836 }
    00837
    00846 bool SafeSaveOrLoad(const char *filename, int mode, int newgm, Subdirectory subdir)
    00847 {
    00848   byte ogm = _game_mode;
    00849
    00850   _game_mode = newgm;
    00851   assert(mode == SL_LOAD || mode == SL_OLD_LOAD);
    00852   switch (SaveOrLoad(filename, mode, subdir)) {
    00853     case SL_OK: return true;
    00854
    00855     case SL_REINIT:
    00856       switch (ogm) {
    00857         default:
    00858         case GM_MENU:   LoadIntroGame();      break;
    00859         case GM_EDITOR: MakeNewEditorWorld(); break;
    00860       }
    00861       return false;
    00862
    00863     default:
    00864       _game_mode = ogm;
    00865       return false;
    00866   }
    00867 }
    00868
    00869 void SwitchMode(int new_mode)
    00870 {
    00871 #ifdef ENABLE_NETWORK
    00872   /* If we are saving something, the network stays in his current state */
    00873   if (new_mode != SM_SAVE) {
    00874     /* If the network is active, make it not-active */
    00875     if (_networking) {
    00876       if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
    00877         NetworkReboot();
    00878       } else {
    00879         NetworkDisconnect();
    00880       }
    00881     }
    00882
    00883     /* If we are a server, we restart the server */
    00884     if (_is_network_server) {
    00885       /* But not if we are going to the menu */
    00886       if (new_mode != SM_MENU) {
    00887         /* check if we should reload the config */
    00888         if (_settings_client.network.reload_cfg) {
    00889           LoadFromConfig();
    00890           MakeNewgameSettingsLive();
    00891           ResetGRFConfig(false);
    00892         }
    00893         NetworkServerStart();
    00894       } else {
    00895         /* This client no longer wants to be a network-server */
    00896         _is_network_server = false;
    00897       }
    00898     }
    00899   }
    00900 #endif /* ENABLE_NETWORK */
    00901   /* Make sure all AI controllers are gone at quiting game */
    00902   if (new_mode != SM_SAVE) AI::KillAll();
    00903
    00904   switch (new_mode) {
    00905     case SM_EDITOR: /* Switch to scenario editor */
    00906       MakeNewEditorWorld();
    00907       break;
    00908
    00909     case SM_NEWGAME: /* New Game --> 'Random game' */
    00910 #ifdef ENABLE_NETWORK
    00911       if (_network_server) {
    00912         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
    00913       }
    00914 #endif /* ENABLE_NETWORK */
    00915       MakeNewGame(false);
    00916       break;
    00917
    00918     case SM_START_SCENARIO: /* New Game --> Choose one of the preset scenarios */
    00919 #ifdef ENABLE_NETWORK
    00920       if (_network_server) {
    00921         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded scenario)", _file_to_saveload.title);
    00922       }
    00923 #endif /* ENABLE_NETWORK */
    00924       StartScenario();
    00925       break;
    00926
    00927     case SM_LOAD: { /* Load game, Play Scenario */
    00928       ResetGRFConfig(true);
    00929       ResetWindowSystem();
    00930
    00931       if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
    00932         LoadIntroGame();
    00933         SetDParamStr(0, GetSaveLoadErrorString());
    00934         ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
    00935       } else {
    00936         if (_saveload_mode == SLD_LOAD_SCENARIO) {
    00937           StartupEngines();
    00938         }
    00939         /* Update the local company for a loaded game. It is either always
    00940         * company #1 (eg 0) or in the case of a dedicated server a spectator */
    00941         SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
    00942         /* Execute the game-start script */
    00943         IConsoleCmdExec("exec scripts/game_start.scr 0");
    00944         /* Decrease pause counter (was increased from opening load dialog) */
    00945         DoCommandP(0, 0, 0, CMD_PAUSE);
    00946 #ifdef ENABLE_NETWORK
    00947         if (_network_server) {
    00948           snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
    00949         }
    00950 #endif /* ENABLE_NETWORK */
    00951       }
    00952       break;
    00953     }
    00954
    00955     case SM_START_HEIGHTMAP: /* Load a heightmap and start a new game from it */
    00956 #ifdef ENABLE_NETWORK
    00957       if (_network_server) {
    00958         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
    00959       }
    00960 #endif /* ENABLE_NETWORK */
    00961       MakeNewGame(true);
    00962       break;
    00963
    00964     case SM_LOAD_HEIGHTMAP: /* Load heightmap from scenario editor */
    00965       SetLocalCompany(OWNER_NONE);
    00966
    00967       GenerateWorld(GW_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
    00968       MarkWholeScreenDirty();
    00969       break;
    00970
    00971     case SM_LOAD_SCENARIO: { /* Load scenario from scenario editor */
    00972       if (SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
    00973         SetLocalCompany(OWNER_NONE);
    00974         _settings_newgame.game_creation.starting_year = _cur_year;
    00975       } else {
    00976         SetDParamStr(0, GetSaveLoadErrorString());
    00977         ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
    00978       }
    00979       break;
    00980     }
    00981
    00982     case SM_MENU: /* Switch to game intro menu */
    00983       LoadIntroGame();
    00984       break;
    00985
    00986     case SM_SAVE: /* Save game */
    00987       /* Make network saved games on pause compatible to singleplayer */
    00988       if (_networking && _pause_game == 1) _pause_game = 2;
    00989       if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
    00990         SetDParamStr(0, GetSaveLoadErrorString());
    00991         ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
    00992       } else {
    00993         DeleteWindowById(WC_SAVELOAD, 0);
    00994       }
    00995       if (_networking && _pause_game == 2) _pause_game = 1;
    00996       break;
    00997
    00998     case SM_GENRANDLAND: /* Generate random land within scenario editor */
    00999       SetLocalCompany(OWNER_NONE);
    01000       GenerateWorld(GW_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
    01001       /* XXX: set date */
    01002       MarkWholeScreenDirty();
    01003       break;
    01004   }
    01005
    01006   if (_switch_mode_errorstr != INVALID_STRING_ID) {
    01007     ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
    01008   }
    01009 }
    01010
    01011
    01017 void StateGameLoop()
    01018 {
    01019   /* dont execute the state loop during pause */
    01020   if (_pause_game) {
    01021     CallWindowTickEvent();
    01022     return;
    01023   }
    01024   if (IsGeneratingWorld()) return;
    01025
    01026   ClearStorageChanges(false);
    01027
    01028   if (_game_mode == GM_EDITOR) {
    01029     RunTileLoop();
    01030     CallVehicleTicks();
    01031     CallLandscapeTick();
    01032     ClearStorageChanges(true);
    01033
    01034     CallWindowTickEvent();
    01035     NewsLoop();
    01036   } else {
    01037     if (_debug_desync_level > 1) {
    01038       Vehicle *v;
    01039       FOR_ALL_VEHICLES(v) {
    01040         if (v != v->First()) continue;
    01041
    01042         switch (v->type) {
    01043           case VEH_ROAD: {
    01044             extern byte GetRoadVehLength(const Vehicle *v);
    01045             if (GetRoadVehLength(v) != v->u.road.cached_veh_length) {
    01046               DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
    01047             }
    01048           } break;
    01049
    01050           case VEH_TRAIN: {
    01051             uint length = 0;
    01052             for (Vehicle *u = v; u != NULL; u = u->Next()) length++;
    01053
    01054             VehicleRail *wagons = MallocT<VehicleRail>(length);
    01055             length = 0;
    01056             for (Vehicle *u = v; u != NULL; u = u->Next()) wagons[length++] = u->u.rail;
    01057
    01058             TrainConsistChanged(v, true);
    01059
    01060             length = 0;
    01061             for (Vehicle *u = v; u != NULL; u = u->Next()) {
    01062               if (memcmp(&wagons[length], &u->u.rail, sizeof(VehicleRail)) != 0) {
    01063                 DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i, wagon %i\n", v->index, (int)v->owner, v->unitnumber, length);
    01064               }
    01065               length++;
    01066             }
    01067
    01068             free(wagons);
    01069           } break;
    01070
    01071           case VEH_AIRCRAFT: {
    01072             uint speed = v->u.air.cached_max_speed;
    01073             UpdateAircraftCache(v);
    01074             if (speed != v->u.air.cached_max_speed) {
    01075               DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
    01076             }
    01077           } break;
    01078
    01079           default:
    01080             break;
    01081         }
    01082       }
    01083     }
    01084
    01085     /* All these actions has to be done from OWNER_NONE
    01086      *  for multiplayer compatibility */
    01087     CompanyID old_company = _current_company;
    01088     _current_company = OWNER_NONE;
    01089
    01090     AnimateAnimatedTiles();
    01091     IncreaseDate();
    01092     RunTileLoop();
    01093     CallVehicleTicks();
    01094     CallLandscapeTick();
    01095     ClearStorageChanges(true);
    01096
    01097     AI::GameLoop();
    01098
    01099     CallWindowTickEvent();
    01100     NewsLoop();
    01101     _current_company = old_company;
    01102   }
    01103 }
    01104
    01107 static void DoAutosave()
    01108 {
    01109   char buf[MAX_PATH];
    01110
    01111 #if defined(PSP)
    01112   /* Autosaving in networking is too time expensive for the PSP */
    01113   if (_networking) return;
    01114 #endif /* PSP */
    01115
    01116   if (_settings_client.gui.keep_all_autosave && _local_company != COMPANY_SPECTATOR) {
    01117     GenerateDefaultSaveName(buf, lastof(buf));
    01118     strecat(buf, ".sav", lastof(buf));
    01119   } else {
    01120     /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
    01121     snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
    01122
    01123     if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
    01124   }
    01125
    01126   DEBUG(sl, 2, "Autosaving to '%s'", buf);
    01127   if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
    01128     ShowErrorMessage(INVALID_STRING_ID, STR_AUTOSAVE_FAILED, 0, 0);
    01129   }
    01130 }
    01131
    01132 void GameLoop()
    01133 {
    01134   ProcessAsyncSaveFinish();
    01135
    01136   /* autosave game? */
    01137   if (_do_autosave) {
    01138     _do_autosave = false;
    01139     DoAutosave();
    01140     RedrawAutosave();
    01141   }
    01142
    01143   /* make a screenshot? */
    01144   if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
    01145
    01146   /* switch game mode? */
    01147   if (_switch_mode != SM_NONE) {
    01148     SwitchMode(_switch_mode);
    01149     _switch_mode = SM_NONE;
    01150   }
    01151
    01152   IncreaseSpriteLRU();
    01153   InteractiveRandom();
    01154
    01155   _caret_timer += 3;
    01156   _palette_animation_counter += 8;
    01157   CursorTick();
    01158
    01159 #ifdef ENABLE_NETWORK
    01160   /* Check for UDP stuff */
    01161   if (_network_available) NetworkUDPGameLoop();
    01162
    01163   if (_networking && !IsGeneratingWorld()) {
    01164     /* Multiplayer */
    01165     NetworkGameLoop();
    01166   } else {
    01167     if (_network_reconnect > 0 && --_network_reconnect == 0) {
    01168       /* This means that we want to reconnect to the last host
    01169        * We do this here, because it means that the network is really closed */
    01170       _network_playas = COMPANY_SPECTATOR;
    01171       NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
    01172     }
    01173     /* Singleplayer */
    01174     StateGameLoop();
    01175   }
    01176 #else
    01177   StateGameLoop();
    01178 #endif /* ENABLE_NETWORK */
    01179
    01180   if (!_pause_game && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
    01181
    01182   if (!_pause_game || _cheats.build_in_pause.value) MoveAllTextEffects();
    01183
    01184   InputLoop();
    01185
    01186   _sound_driver->MainLoop();
    01187   MusicLoop();
    01188 }