openttd.cpp

Go to the documentation of this file.
00001 /* $Id: openttd.cpp 15645 2009-03-08 16:51:08Z frosch $ */
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   _engine_mngr.ResetToDefaultMapping();
00290   _house_mngr.ResetMapping();
00291   _industry_mngr.ResetMapping();
00292   _industile_mngr.ResetMapping();
00293   _Company_pool.AddBlockToPool();
00294 }
00295 
00296 
00300 static void ShutdownGame()
00301 {
00302   /* stop the AI */
00303   AI::Uninitialize(false);
00304 
00305   IConsoleFree();
00306 
00307   if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
00308 
00309   DriverFactoryBase::ShutdownDrivers();
00310 
00311   UnInitWindowSystem();
00312 
00313   /* Uninitialize airport state machines */
00314   UnInitializeAirports();
00315 
00316   /* Uninitialize variables that are allocated dynamically */
00317   GamelogReset();
00318   _Town_pool.CleanPool();
00319   _Industry_pool.CleanPool();
00320   _Station_pool.CleanPool();
00321   _Vehicle_pool.CleanPool();
00322   _Sign_pool.CleanPool();
00323   _Order_pool.CleanPool();
00324   _Group_pool.CleanPool();
00325   _CargoPacket_pool.CleanPool();
00326   _Engine_pool.CleanPool();
00327   _Company_pool.CleanPool();
00328 
00329   free(_config_file);
00330 
00331   /* Close all and any open filehandles */
00332   FioCloseAll();
00333 }
00334 
00335 static void LoadIntroGame()
00336 {
00337   _game_mode = GM_MENU;
00338 
00339   ResetGRFConfig(false);
00340 
00341   /* Setup main window */
00342   ResetWindowSystem();
00343   SetupColoursAndInitialWindow();
00344 
00345   /* Load the default opening screen savegame */
00346   if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
00347     GenerateWorld(GW_EMPTY, 64, 64); // if failed loading, make empty world.
00348     WaitTillGeneratedWorld();
00349     SetLocalCompany(COMPANY_SPECTATOR);
00350   } else {
00351     SetLocalCompany(COMPANY_FIRST);
00352   }
00353 
00354   _pause_game = 0;
00355   _cursor.fix_at = false;
00356 
00357   CheckForMissingGlyphsInLoadedLanguagePack();
00358 
00359   /* Play main theme */
00360   if (_music_driver->IsSongPlaying()) ResetMusic();
00361 }
00362 
00363 void MakeNewgameSettingsLive()
00364 {
00365   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00366     if (_settings_game.ai_config[c] != NULL) {
00367       delete _settings_game.ai_config[c];
00368     }
00369   }
00370 
00371   _settings_game = _settings_newgame;
00372 
00373   for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00374     _settings_game.ai_config[c] = NULL;
00375     if (_settings_newgame.ai_config[c] != NULL) {
00376       _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
00377     }
00378   }
00379 }
00380 
00381 byte _savegame_sort_order;
00382 #if defined(UNIX) && !defined(__MORPHOS__)
00383 extern void DedicatedFork();
00384 #endif
00385 
00386 int ttd_main(int argc, char *argv[])
00387 {
00388   int i;
00389   const char *optformat;
00390   char *musicdriver = NULL;
00391   char *sounddriver = NULL;
00392   char *videodriver = NULL;
00393   char *blitter = NULL;
00394   char *graphics_set = NULL;
00395   Dimension resolution = {0, 0};
00396   Year startyear = INVALID_YEAR;
00397   uint generation_seed = GENERATE_NEW_SEED;
00398   bool save_config = true;
00399 #if defined(ENABLE_NETWORK)
00400   bool dedicated = false;
00401   bool network   = false;
00402   char *network_conn = NULL;
00403   char *debuglog_conn = NULL;
00404   char *dedicated_host = NULL;
00405   uint16 dedicated_port = 0;
00406 #endif /* ENABLE_NETWORK */
00407 
00408   _game_mode = GM_MENU;
00409   _switch_mode = SM_MENU;
00410   _switch_mode_errorstr = INVALID_STRING_ID;
00411   _dedicated_forks = false;
00412   _config_file = NULL;
00413 
00414   /* The last param of the following function means this:
00415    *   a letter means: it accepts that param (e.g.: -h)
00416    *   a ':' behind it means: it need a param (e.g.: -m<driver>)
00417    *   a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
00418   optformat = "m:s:v:b:hD::n::ei::I:t:d::r:g::G:c:xl:"
00419 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00420     "f"
00421 #endif
00422   ;
00423 
00424   MyGetOptData mgo(argc - 1, argv + 1, optformat);
00425 
00426   while ((i = MyGetOpt(&mgo)) != -1) {
00427     switch (i) {
00428     case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
00429     case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
00430     case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
00431     case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
00432     case 'b': free(blitter); blitter = strdup(mgo.opt); break;
00433 #if defined(ENABLE_NETWORK)
00434     case 'D':
00435       free(musicdriver);
00436       free(sounddriver);
00437       free(videodriver);
00438       free(blitter);
00439       musicdriver = strdup("null");
00440       sounddriver = strdup("null");
00441       videodriver = strdup("dedicated");
00442       blitter = strdup("null");
00443       dedicated = true;
00444       SetDebugString("net=6");
00445       if (mgo.opt != NULL) {
00446         /* Use the existing method for parsing (openttd -n).
00447          * However, we do ignore the #company part. */
00448         const char *temp = NULL;
00449         const char *port = NULL;
00450         ParseConnectionString(&temp, &port, mgo.opt);
00451         if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
00452         if (port != NULL) dedicated_port = atoi(port);
00453       }
00454       break;
00455     case 'f': _dedicated_forks = true; break;
00456     case 'n':
00457       network = true;
00458       network_conn = mgo.opt; // optional IP parameter, NULL if unset
00459       break;
00460     case 'l':
00461       debuglog_conn = mgo.opt;
00462       break;
00463 #endif /* ENABLE_NETWORK */
00464     case 'r': ParseResolution(&resolution, mgo.opt); break;
00465     case 't': startyear = atoi(mgo.opt); break;
00466     case 'd': {
00467 #if defined(WIN32)
00468         CreateConsole();
00469 #endif
00470         if (mgo.opt != NULL) SetDebugString(mgo.opt);
00471       } break;
00472     case 'e': _switch_mode = SM_EDITOR; break;
00473     case 'i':
00474       /* there is an argument, it is not empty, and it is exactly 1 char long */
00475       if (!StrEmpty(mgo.opt) && mgo.opt[1] == '\0') {
00476         _use_palette = (PaletteType)(mgo.opt[0] - '0');
00477         if (_use_palette <= MAX_PAL) break;
00478       }
00479       usererror("Valid value for '-i' is 0, 1 or 2");
00480     case 'g':
00481       if (mgo.opt != NULL) {
00482         strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
00483         _switch_mode = SM_LOAD;
00484         _file_to_saveload.mode = SL_LOAD;
00485 
00486         /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
00487         const char *t = strrchr(_file_to_saveload.name, '.');
00488         if (t != NULL) {
00489           FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
00490           if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
00491         }
00492 
00493         break;
00494       }
00495 
00496       _switch_mode = SM_NEWGAME;
00497       /* Give a random map if no seed has been given */
00498       if (generation_seed == GENERATE_NEW_SEED) {
00499         generation_seed = InteractiveRandom();
00500       }
00501       break;
00502     case 'G': generation_seed = atoi(mgo.opt); break;
00503     case 'c': _config_file = strdup(mgo.opt); break;
00504     case 'x': save_config = false; break;
00505     case -2:
00506     case 'h':
00507       /* The next two functions are needed to list the graphics sets.
00508        * We can't do them earlier because then we can't show it on
00509        * the debug console as that hasn't been configured yet. */
00510       DeterminePaths(argv[0]);
00511       FindGraphicsSets();
00512       ShowHelp();
00513       return 0;
00514     }
00515   }
00516 
00517 #if defined(WINCE) && defined(_DEBUG)
00518   /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
00519   SetDebugString("4");
00520 #endif
00521 
00522   DeterminePaths(argv[0]);
00523   FindGraphicsSets();
00524 
00525 #if defined(UNIX) && !defined(__MORPHOS__)
00526   /* We must fork here, or we'll end up without some resources we need (like sockets) */
00527   if (_dedicated_forks)
00528     DedicatedFork();
00529 #endif
00530 
00531   AI::Initialize();
00532   LoadFromConfig();
00533   AI::Uninitialize(true);
00534   CheckConfig();
00535   LoadFromHighScore();
00536 
00537   if (resolution.width != 0) { _cur_resolution = resolution; }
00538   if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
00539   if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
00540 
00541   /* The width and height must be at least 1 pixel, this
00542    * way all internal drawing routines work correctly. */
00543   if (_cur_resolution.width  <= 0) _cur_resolution.width  = 1;
00544   if (_cur_resolution.height <= 0) _cur_resolution.height = 1;
00545 
00546 #if defined(ENABLE_NETWORK)
00547   if (dedicated_host) snprintf(_settings_client.network.server_bind_ip, sizeof(_settings_client.network.server_bind_ip), "%s", dedicated_host);
00548   if (dedicated_port) _settings_client.network.server_port = dedicated_port;
00549   if (_dedicated_forks && !dedicated) _dedicated_forks = false;
00550 #endif /* ENABLE_NETWORK */
00551 
00552   /* enumerate language files */
00553   InitializeLanguagePacks();
00554 
00555   /* initialize screenshot formats */
00556   InitializeScreenshotFormats();
00557 
00558   /* initialize airport state machines */
00559   InitializeAirports();
00560 
00561   /* initialize all variables that are allocated dynamically */
00562   InitializeDynamicVariables();
00563 
00564   /* Sample catalogue */
00565   DEBUG(misc, 1, "Loading sound effects...");
00566   MxInitialize(11025);
00567   SoundInitialize("sample.cat");
00568 
00569   /* Initialize FreeType */
00570   InitFreeType();
00571 
00572   /* This must be done early, since functions use the InvalidateWindow* calls */
00573   InitWindowSystem();
00574 
00575   if (graphics_set == NULL) graphics_set = _ini_graphics_set;
00576   if (!SetGraphicsSet(graphics_set)) {
00577     StrEmpty(graphics_set) ?
00578       usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD.") :
00579       usererror("Failed to select requested graphics set '%s'", graphics_set);
00580   }
00581 
00582   /* Initialize game palette */
00583   GfxInitPalettes();
00584 
00585   DEBUG(misc, 1, "Loading blitter...");
00586   if (blitter == NULL) blitter = _ini_blitter;
00587   if (BlitterFactoryBase::SelectBlitter(blitter) == NULL)
00588     StrEmpty(blitter) ?
00589       usererror("Failed to autoprobe blitter") :
00590       usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
00591 
00592   DEBUG(driver, 1, "Loading drivers...");
00593 
00594   if (sounddriver == NULL) sounddriver = _ini_sounddriver;
00595   _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
00596   if (_sound_driver == NULL) {
00597     StrEmpty(sounddriver) ?
00598       usererror("Failed to autoprobe sound driver") :
00599       usererror("Failed to select requested sound driver '%s'", sounddriver);
00600   }
00601 
00602   if (musicdriver == NULL) musicdriver = _ini_musicdriver;
00603   _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
00604   if (_music_driver == NULL) {
00605     StrEmpty(musicdriver) ?
00606       usererror("Failed to autoprobe music driver") :
00607       usererror("Failed to select requested music driver '%s'", musicdriver);
00608   }
00609 
00610   if (videodriver == NULL) videodriver = _ini_videodriver;
00611   _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
00612   if (_video_driver == NULL) {
00613     StrEmpty(videodriver) ?
00614       usererror("Failed to autoprobe video driver") :
00615       usererror("Failed to select requested video driver '%s'", videodriver);
00616   }
00617 
00618   _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
00619   /* Initialize the zoom level of the screen to normal */
00620   _screen.zoom = ZOOM_LVL_NORMAL;
00621 
00622   /* restore saved music volume */
00623   _music_driver->SetVolume(msf.music_vol);
00624 
00625   NetworkStartUp(); // initialize network-core
00626 
00627 #if defined(ENABLE_NETWORK)
00628   if (debuglog_conn != NULL && _network_available) {
00629     const char *not_used = NULL;
00630     const char *port = NULL;
00631     uint16 rport;
00632 
00633     rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
00634 
00635     ParseConnectionString(&not_used, &port, debuglog_conn);
00636     if (port != NULL) rport = atoi(port);
00637 
00638     NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
00639   }
00640 #endif /* ENABLE_NETWORK */
00641 
00642   ScanNewGRFFiles();
00643 
00644   ResetGRFConfig(false);
00645 
00646   /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
00647   if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
00648 
00649   /* initialize the ingame console */
00650   IConsoleInit();
00651   _cursor.in_window = true;
00652   InitializeGUI();
00653   IConsoleCmdExec("exec scripts/autoexec.scr 0");
00654 
00655   GenerateWorld(GW_EMPTY, 64, 64); // Make the viewport initialization happy
00656   WaitTillGeneratedWorld();
00657 
00658   CheckForMissingGlyphsInLoadedLanguagePack();
00659 
00660 #ifdef ENABLE_NETWORK
00661   if (network && _network_available) {
00662     if (network_conn != NULL) {
00663       const char *port = NULL;
00664       const char *company = NULL;
00665       uint16 rport;
00666 
00667       rport = NETWORK_DEFAULT_PORT;
00668       _network_playas = COMPANY_NEW_COMPANY;
00669 
00670       ParseConnectionString(&company, &port, network_conn);
00671 
00672       if (company != NULL) {
00673         _network_playas = (CompanyID)atoi(company);
00674 
00675         if (_network_playas != COMPANY_SPECTATOR) {
00676           _network_playas--;
00677           if (_network_playas >= MAX_COMPANIES) return false;
00678         }
00679       }
00680       if (port != NULL) rport = atoi(port);
00681 
00682       LoadIntroGame();
00683       _switch_mode = SM_NONE;
00684       NetworkClientConnectGame(NetworkAddress(network_conn, rport));
00685     }
00686   }
00687 #endif /* ENABLE_NETWORK */
00688 
00689   _video_driver->MainLoop();
00690 
00691   WaitTillSaved();
00692 
00693   /* only save config if we have to */
00694   if (save_config) {
00695     SaveToConfig();
00696     SaveToHighScore();
00697   }
00698 
00699   /* Reset windowing system, stop drivers, free used memory, ... */
00700   ShutdownGame();
00701 
00702   return 0;
00703 }
00704 
00705 void HandleExitGameRequest()
00706 {
00707   if (_game_mode == GM_MENU) { // do not ask to quit on the main screen
00708     _exit_game = true;
00709   } else if (_settings_client.gui.autosave_on_exit) {
00710     DoExitSave();
00711     _exit_game = true;
00712   } else {
00713     AskExitGame();
00714   }
00715 }
00716 
00717 static void ShowScreenshotResult(bool b)
00718 {
00719   if (b) {
00720     extern char _screenshot_name[];
00721     SetDParamStr(0, _screenshot_name);
00722     ShowErrorMessage(INVALID_STRING_ID, STR_031B_SCREENSHOT_SUCCESSFULLY, 0, 0);
00723   } else {
00724     ShowErrorMessage(INVALID_STRING_ID, STR_031C_SCREENSHOT_FAILED, 0, 0);
00725   }
00726 
00727 }
00728 
00729 static void MakeNewGameDone()
00730 {
00731   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
00732 
00733   /* In a dedicated server, the server does not play */
00734   if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0) {
00735     SetLocalCompany(COMPANY_SPECTATOR);
00736     IConsoleCmdExec("exec scripts/game_start.scr 0");
00737     return;
00738   }
00739 
00740   /* Create a single company */
00741   DoStartupNewCompany(false);
00742 
00743   IConsoleCmdExec("exec scripts/game_start.scr 0");
00744 
00745   SetLocalCompany(COMPANY_FIRST);
00746   _current_company = _local_company;
00747   DoCommandP(0, (_settings_client.gui.autorenew << 15 ) | (_settings_client.gui.autorenew_months << 16) | 4, _settings_client.gui.autorenew_money, CMD_SET_AUTOREPLACE);
00748 
00749   InitializeRailGUI();
00750 
00751 #ifdef ENABLE_NETWORK
00752   /* We are the server, we start a new company (not dedicated),
00753    * so set the default password *if* needed. */
00754   if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00755     char *password = _settings_client.network.default_company_pass;
00756     NetworkChangeCompanyPassword(1, &password);
00757   }
00758 #endif /* ENABLE_NETWORK */
00759 
00760   MarkWholeScreenDirty();
00761 }
00762 
00763 static void MakeNewGame(bool from_heightmap)
00764 {
00765   _game_mode = GM_NORMAL;
00766 
00767   ResetGRFConfig(true);
00768   _engine_mngr.ResetToDefaultMapping();
00769   _house_mngr.ResetMapping();
00770   _industile_mngr.ResetMapping();
00771   _industry_mngr.ResetMapping();
00772 
00773   GenerateWorldSetCallback(&MakeNewGameDone);
00774   GenerateWorld(from_heightmap ? GW_HEIGHTMAP : GW_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00775 }
00776 
00777 static void MakeNewEditorWorldDone()
00778 {
00779   SetLocalCompany(OWNER_NONE);
00780 }
00781 
00782 static void MakeNewEditorWorld()
00783 {
00784   _game_mode = GM_EDITOR;
00785 
00786   ResetGRFConfig(true);
00787 
00788   GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00789   GenerateWorld(GW_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00790 }
00791 
00792 void StartupCompanies();
00793 void StartupDisasters();
00794 extern void StartupEconomy();
00795 
00801 static void StartScenario()
00802 {
00803   _game_mode = GM_NORMAL;
00804 
00805   /* invalid type */
00806   if (_file_to_saveload.mode == SL_INVALID) {
00807     DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
00808     SetDParamStr(0, GetSaveLoadErrorString());
00809     ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
00810     _game_mode = GM_MENU;
00811     return;
00812   }
00813 
00814   /* Reinitialize windows */
00815   ResetWindowSystem();
00816 
00817   SetupColoursAndInitialWindow();
00818 
00819   ResetGRFConfig(true);
00820 
00821   /* Load game */
00822   if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, SCENARIO_DIR) != SL_OK) {
00823     LoadIntroGame();
00824     SetDParamStr(0, GetSaveLoadErrorString());
00825     ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
00826   }
00827 
00828   _settings_game.difficulty = _settings_newgame.difficulty;
00829 
00830   /* Inititalize data */
00831   StartupEconomy();
00832   StartupCompanies();
00833   StartupEngines();
00834   StartupDisasters();
00835 
00836   SetLocalCompany(COMPANY_FIRST);
00837   _current_company = _local_company;
00838   DoCommandP(0, (_settings_client.gui.autorenew << 15 ) | (_settings_client.gui.autorenew_months << 16) | 4, _settings_client.gui.autorenew_money, CMD_SET_AUTOREPLACE);
00839 
00840   MarkWholeScreenDirty();
00841 }
00842 
00851 bool SafeSaveOrLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir)
00852 {
00853   GameMode ogm = _game_mode;
00854 
00855   _game_mode = newgm;
00856   assert(mode == SL_LOAD || mode == SL_OLD_LOAD);
00857   switch (SaveOrLoad(filename, mode, subdir)) {
00858     case SL_OK: return true;
00859 
00860     case SL_REINIT:
00861       switch (ogm) {
00862         default:
00863         case GM_MENU:   LoadIntroGame();      break;
00864         case GM_EDITOR: MakeNewEditorWorld(); break;
00865       }
00866       return false;
00867 
00868     default:
00869       _game_mode = ogm;
00870       return false;
00871   }
00872 }
00873 
00874 void SwitchToMode(SwitchMode new_mode)
00875 {
00876 #ifdef ENABLE_NETWORK
00877   /* If we are saving something, the network stays in his current state */
00878   if (new_mode != SM_SAVE) {
00879     /* If the network is active, make it not-active */
00880     if (_networking) {
00881       if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
00882         NetworkReboot();
00883       } else {
00884         NetworkDisconnect();
00885       }
00886     }
00887 
00888     /* If we are a server, we restart the server */
00889     if (_is_network_server) {
00890       /* But not if we are going to the menu */
00891       if (new_mode != SM_MENU) {
00892         /* check if we should reload the config */
00893         if (_settings_client.network.reload_cfg) {
00894           LoadFromConfig();
00895           MakeNewgameSettingsLive();
00896           ResetGRFConfig(false);
00897         }
00898         NetworkServerStart();
00899       } else {
00900         /* This client no longer wants to be a network-server */
00901         _is_network_server = false;
00902       }
00903     }
00904   }
00905 #endif /* ENABLE_NETWORK */
00906   /* Make sure all AI controllers are gone at quiting game */
00907   if (new_mode != SM_SAVE) AI::KillAll();
00908 
00909   switch (new_mode) {
00910     case SM_EDITOR: /* Switch to scenario editor */
00911       MakeNewEditorWorld();
00912       break;
00913 
00914     case SM_NEWGAME: /* New Game --> 'Random game' */
00915 #ifdef ENABLE_NETWORK
00916       if (_network_server) {
00917         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
00918       }
00919 #endif /* ENABLE_NETWORK */
00920       MakeNewGame(false);
00921       break;
00922 
00923     case SM_START_SCENARIO: /* New Game --> Choose one of the preset scenarios */
00924 #ifdef ENABLE_NETWORK
00925       if (_network_server) {
00926         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded scenario)", _file_to_saveload.title);
00927       }
00928 #endif /* ENABLE_NETWORK */
00929       StartScenario();
00930       break;
00931 
00932     case SM_LOAD: { /* Load game, Play Scenario */
00933       ResetGRFConfig(true);
00934       ResetWindowSystem();
00935 
00936       if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
00937         LoadIntroGame();
00938         SetDParamStr(0, GetSaveLoadErrorString());
00939         ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
00940       } else {
00941         if (_saveload_mode == SLD_LOAD_SCENARIO) {
00942           StartupEngines();
00943         }
00944         /* Update the local company for a loaded game. It is either always
00945         * company #1 (eg 0) or in the case of a dedicated server a spectator */
00946         SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
00947         /* Execute the game-start script */
00948         IConsoleCmdExec("exec scripts/game_start.scr 0");
00949         /* Decrease pause counter (was increased from opening load dialog) */
00950         DoCommandP(0, 0, 0, CMD_PAUSE);
00951 #ifdef ENABLE_NETWORK
00952         if (_network_server) {
00953           snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
00954         }
00955 #endif /* ENABLE_NETWORK */
00956       }
00957       break;
00958     }
00959 
00960     case SM_START_HEIGHTMAP: /* Load a heightmap and start a new game from it */
00961 #ifdef ENABLE_NETWORK
00962       if (_network_server) {
00963         snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
00964       }
00965 #endif /* ENABLE_NETWORK */
00966       MakeNewGame(true);
00967       break;
00968 
00969     case SM_LOAD_HEIGHTMAP: /* Load heightmap from scenario editor */
00970       SetLocalCompany(OWNER_NONE);
00971 
00972       GenerateWorld(GW_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00973       MarkWholeScreenDirty();
00974       break;
00975 
00976     case SM_LOAD_SCENARIO: { /* Load scenario from scenario editor */
00977       if (SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
00978         SetLocalCompany(OWNER_NONE);
00979         _settings_newgame.game_creation.starting_year = _cur_year;
00980       } else {
00981         SetDParamStr(0, GetSaveLoadErrorString());
00982         ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
00983       }
00984       break;
00985     }
00986 
00987     case SM_MENU: /* Switch to game intro menu */
00988       LoadIntroGame();
00989       break;
00990 
00991     case SM_SAVE: /* Save game */
00992       /* Make network saved games on pause compatible to singleplayer */
00993       if (_networking && _pause_game == 1) _pause_game = 2;
00994       if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
00995         SetDParamStr(0, GetSaveLoadErrorString());
00996         ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
00997       } else {
00998         DeleteWindowById(WC_SAVELOAD, 0);
00999       }
01000       if (_networking && _pause_game == 2) _pause_game = 1;
01001       break;
01002 
01003     case SM_GENRANDLAND: /* Generate random land within scenario editor */
01004       SetLocalCompany(OWNER_NONE);
01005       GenerateWorld(GW_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01006       /* XXX: set date */
01007       MarkWholeScreenDirty();
01008       break;
01009 
01010     default: NOT_REACHED();
01011   }
01012 
01013   if (_switch_mode_errorstr != INVALID_STRING_ID) {
01014     ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
01015   }
01016 }
01017 
01018 
01024 void StateGameLoop()
01025 {
01026   /* dont execute the state loop during pause */
01027   if (_pause_game) {
01028     CallWindowTickEvent();
01029     return;
01030   }
01031   if (IsGeneratingWorld()) return;
01032 
01033   ClearStorageChanges(false);
01034 
01035   if (_game_mode == GM_EDITOR) {
01036     RunTileLoop();
01037     CallVehicleTicks();
01038     CallLandscapeTick();
01039     ClearStorageChanges(true);
01040 
01041     CallWindowTickEvent();
01042     NewsLoop();
01043   } else {
01044     if (_debug_desync_level > 1) {
01045       Vehicle *v;
01046       FOR_ALL_VEHICLES(v) {
01047         if (v != v->First()) continue;
01048 
01049         switch (v->type) {
01050           case VEH_ROAD: {
01051             extern byte GetRoadVehLength(const Vehicle *v);
01052             if (GetRoadVehLength(v) != v->u.road.cached_veh_length) {
01053               DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
01054             }
01055           } break;
01056 
01057           case VEH_TRAIN: {
01058             uint length = 0;
01059             for (Vehicle *u = v; u != NULL; u = u->Next()) length++;
01060 
01061             VehicleRail *wagons = MallocT<VehicleRail>(length);
01062             length = 0;
01063             for (Vehicle *u = v; u != NULL; u = u->Next()) wagons[length++] = u->u.rail;
01064 
01065             TrainConsistChanged(v, true);
01066 
01067             length = 0;
01068             for (Vehicle *u = v; u != NULL; u = u->Next()) {
01069               if (memcmp(&wagons[length], &u->u.rail, sizeof(VehicleRail)) != 0) {
01070                 DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i, wagon %i\n", v->index, (int)v->owner, v->unitnumber, length);
01071               }
01072               length++;
01073             }
01074 
01075             free(wagons);
01076           } break;
01077 
01078           case VEH_AIRCRAFT: {
01079             uint speed = v->u.air.cached_max_speed;
01080             UpdateAircraftCache(v);
01081             if (speed != v->u.air.cached_max_speed) {
01082               DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
01083             }
01084           } break;
01085 
01086           default:
01087             break;
01088         }
01089       }
01090     }
01091 
01092     /* All these actions has to be done from OWNER_NONE
01093      *  for multiplayer compatibility */
01094     CompanyID old_company = _current_company;
01095     _current_company = OWNER_NONE;
01096 
01097     AnimateAnimatedTiles();
01098     IncreaseDate();
01099     RunTileLoop();
01100     CallVehicleTicks();
01101     CallLandscapeTick();
01102     ClearStorageChanges(true);
01103 
01104     AI::GameLoop();
01105 
01106     CallWindowTickEvent();
01107     NewsLoop();
01108     _current_company = old_company;
01109   }
01110 }
01111 
01114 static void DoAutosave()
01115 {
01116   char buf[MAX_PATH];
01117 
01118 #if defined(PSP)
01119   /* Autosaving in networking is too time expensive for the PSP */
01120   if (_networking) return;
01121 #endif /* PSP */
01122 
01123   if (_settings_client.gui.keep_all_autosave) {
01124     GenerateDefaultSaveName(buf, lastof(buf));
01125     strecat(buf, ".sav", lastof(buf));
01126   } else {
01127     /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
01128     snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01129 
01130     if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01131   }
01132 
01133   DEBUG(sl, 2, "Autosaving to '%s'", buf);
01134   if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01135     ShowErrorMessage(INVALID_STRING_ID, STR_AUTOSAVE_FAILED, 0, 0);
01136   }
01137 }
01138 
01139 void GameLoop()
01140 {
01141   ProcessAsyncSaveFinish();
01142 
01143   /* autosave game? */
01144   if (_do_autosave) {
01145     _do_autosave = false;
01146     DoAutosave();
01147     RedrawAutosave();
01148   }
01149 
01150   /* make a screenshot? */
01151   if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
01152 
01153   /* switch game mode? */
01154   if (_switch_mode != SM_NONE) {
01155     SwitchToMode(_switch_mode);
01156     _switch_mode = SM_NONE;
01157   }
01158 
01159   IncreaseSpriteLRU();
01160   InteractiveRandom();
01161 
01162   extern int _caret_timer;
01163   _caret_timer += 3;
01164   _palette_animation_counter += 8;
01165   CursorTick();
01166 
01167 #ifdef ENABLE_NETWORK
01168   /* Check for UDP stuff */
01169   if (_network_available) NetworkUDPGameLoop();
01170 
01171   if (_networking && !IsGeneratingWorld()) {
01172     /* Multiplayer */
01173     NetworkGameLoop();
01174   } else {
01175     if (_network_reconnect > 0 && --_network_reconnect == 0) {
01176       /* This means that we want to reconnect to the last host
01177        * We do this here, because it means that the network is really closed */
01178       _network_playas = COMPANY_SPECTATOR;
01179       NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
01180     }
01181     /* Singleplayer */
01182     StateGameLoop();
01183   }
01184 #else
01185   StateGameLoop();
01186 #endif /* ENABLE_NETWORK */
01187 
01188   if (!_pause_game && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01189 
01190   if (!_pause_game || _cheats.build_in_pause.value) MoveAllTextEffects();
01191 
01192   InputLoop();
01193 
01194   _sound_driver->MainLoop();
01195   MusicLoop();
01196 }

Generated on Mon Mar 9 23:33:49 2009 for openttd by  doxygen 1.5.6