00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "stdafx.h"
00013
00014 #define VARDEF
00015 #include "variables.h"
00016 #undef VARDEF
00017
00018
00019 #include "blitter/factory.hpp"
00020 #include "sound/sound_driver.hpp"
00021 #include "music/music_driver.hpp"
00022 #include "video/video_driver.hpp"
00023
00024 #include "fontcache.h"
00025 #include "gui.h"
00026 #include "sound_func.h"
00027 #include "window_func.h"
00028
00029 #include "base_media_base.h"
00030 #include "saveload/saveload.h"
00031 #include "landscape.h"
00032 #include "company_func.h"
00033 #include "command_func.h"
00034 #include "news_func.h"
00035 #include "fios.h"
00036 #include "aircraft.h"
00037 #include "roadveh.h"
00038 #include "train.h"
00039 #include "console_func.h"
00040 #include "screenshot.h"
00041 #include "network/network.h"
00042 #include "network/network_func.h"
00043 #include "signs_base.h"
00044 #include "ai/ai.hpp"
00045 #include "ai/ai_config.hpp"
00046 #include "settings_func.h"
00047 #include "genworld.h"
00048 #include "group.h"
00049 #include "strings_func.h"
00050 #include "date_func.h"
00051 #include "vehicle_func.h"
00052 #include "gamelog.h"
00053 #include "cheat_type.h"
00054 #include "animated_tile_func.h"
00055 #include "roadstop_base.h"
00056 #include "functions.h"
00057 #include "elrail_func.h"
00058 #include "rev.h"
00059 #include "highscore.h"
00060 #include "thread/thread.h"
00061 #include "station_base.h"
00062 #include "crashlog.h"
00063 #include "company_base.h"
00064 #include "engine_base.h"
00065 #include "engine_func.h"
00066 #include "core/random_func.hpp"
00067
00068 #include "newgrf_commons.h"
00069
00070 #include "town.h"
00071 #include "industry.h"
00072
00073 #include <stdarg.h>
00074
00075 #include "table/strings.h"
00076
00077 StringID _switch_mode_errorstr;
00078
00079 void CallLandscapeTick();
00080 void IncreaseDate();
00081 void DoPaletteAnimations();
00082 void MusicLoop();
00083 void ResetMusic();
00084 void ProcessAsyncSaveFinish();
00085 void CallWindowTickEvent();
00086
00087 extern void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
00088 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
00089 extern void ShowOSErrorBox(const char *buf, bool system);
00090 extern void InitializeRailGUI();
00091
00097 void CDECL usererror(const char *s, ...)
00098 {
00099 va_list va;
00100 char buf[512];
00101
00102 va_start(va, s);
00103 vsnprintf(buf, lengthof(buf), s, va);
00104 va_end(va);
00105
00106 ShowOSErrorBox(buf, false);
00107 if (_video_driver != NULL) _video_driver->Stop();
00108
00109 exit(1);
00110 }
00111
00117 void CDECL error(const char *s, ...)
00118 {
00119 va_list va;
00120 char buf[512];
00121
00122 va_start(va, s);
00123 vsnprintf(buf, lengthof(buf), s, va);
00124 va_end(va);
00125
00126 ShowOSErrorBox(buf, true);
00127
00128
00129 CrashLog::SetErrorMessage(buf);
00130 abort();
00131 }
00132
00137 void CDECL ShowInfoF(const char *str, ...)
00138 {
00139 va_list va;
00140 char buf[1024];
00141 va_start(va, str);
00142 vsnprintf(buf, lengthof(buf), str, va);
00143 va_end(va);
00144 ShowInfo(buf);
00145 }
00146
00150 static void ShowHelp()
00151 {
00152 char buf[8192];
00153 char *p = buf;
00154
00155 p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
00156 p = strecpy(p,
00157 "\n"
00158 "\n"
00159 "Command line options:\n"
00160 " -v drv = Set video driver (see below)\n"
00161 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
00162 " -m drv = Set music driver (see below)\n"
00163 " -b drv = Set the blitter to use (see below)\n"
00164 " -a ai = Force use of specific AI (see below)\n"
00165 " -r res = Set resolution (for instance 800x600)\n"
00166 " -h = Display this help text\n"
00167 " -t year = Set starting year\n"
00168 " -d [[fac=]lvl[,...]]= Debug mode\n"
00169 " -e = Start Editor\n"
00170 " -g [savegame] = Start new/save game immediately\n"
00171 " -G seed = Set random seed\n"
00172 #if defined(ENABLE_NETWORK)
00173 " -n [ip:port#company]= Start networkgame\n"
00174 " -p password = Password to join server\n"
00175 " -P password = Password to join company\n"
00176 " -D [ip][:port] = Start dedicated server\n"
00177 " -l ip[:port] = Redirect DEBUG()\n"
00178 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00179 " -f = Fork into the background (dedicated only)\n"
00180 #endif
00181 #endif
00182 " -i palette = Force to use the DOS (0) or Windows (1) palette\n"
00183 " (defines default setting when adding newgrfs)\n"
00184 " Default value (2) lets OpenTTD use the palette\n"
00185 " specified in graphics set file (see below)\n"
00186 " -I graphics_set = Force the graphics set (see below)\n"
00187 " -S sounds_set = Force the sounds set (see below)\n"
00188 " -M music_set = Force the music set (see below)\n"
00189 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
00190 " -x = Do not automatically save to config file on exit\n"
00191 "\n",
00192 lastof(buf)
00193 );
00194
00195
00196 p = BaseGraphics::GetSetsList(p, lastof(buf));
00197
00198
00199 p = BaseSounds::GetSetsList(p, lastof(buf));
00200
00201
00202 p = BaseMusic::GetSetsList(p, lastof(buf));
00203
00204
00205 p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
00206
00207
00208 p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
00209
00210
00211 AI::Initialize();
00212 p = AI::GetConsoleList(p, lastof(buf));
00213 AI::Uninitialize(true);
00214
00215
00216
00217 #if !defined(WIN32) && !defined(WIN64)
00218 printf("%s\n", buf);
00219 #else
00220 ShowInfo(buf);
00221 #endif
00222 }
00223
00224
00225 struct MyGetOptData {
00226 char *opt;
00227 int numleft;
00228 char **argv;
00229 const char *options;
00230 char *cont;
00231
00232 MyGetOptData(int argc, char **argv, const char *options)
00233 {
00234 opt = NULL;
00235 numleft = argc;
00236 this->argv = argv;
00237 this->options = options;
00238 cont = NULL;
00239 }
00240 };
00241
00242 static int MyGetOpt(MyGetOptData *md)
00243 {
00244 char *s = md->cont;
00245 if (s != NULL)
00246 goto md_continue_here;
00247
00248 for (;;) {
00249 if (--md->numleft < 0) return -1;
00250
00251 s = *md->argv++;
00252 if (*s == '-') {
00253 md_continue_here:;
00254 s++;
00255 if (*s != 0) {
00256 const char *r;
00257
00258 if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
00259
00260 return -2;
00261 }
00262 if (r[1] == ':') {
00263 char *t;
00264
00265 if (!*(t = s + 1)) {
00266
00267 if (--md->numleft < 0 || *(t = *md->argv) == '-') {
00268
00269 if (r[2] != ':')
00270 return -2;
00271 md->numleft++;
00272 t = NULL;
00273 } else {
00274 md->argv++;
00275 }
00276 }
00277 md->opt = t;
00278 md->cont = NULL;
00279 return *s;
00280 }
00281 md->opt = NULL;
00282 md->cont = s;
00283 return *s;
00284 }
00285 } else {
00286
00287 return -2;
00288 }
00289 }
00290 }
00291
00298 static void ParseResolution(Dimension *res, const char *s)
00299 {
00300 const char *t = strchr(s, 'x');
00301 if (t == NULL) {
00302 ShowInfoF("Invalid resolution '%s'", s);
00303 return;
00304 }
00305
00306 res->width = max(strtoul(s, NULL, 0), 64UL);
00307 res->height = max(strtoul(t + 1, NULL, 0), 64UL);
00308 }
00309
00310 static void InitializeDynamicVariables()
00311 {
00312
00313 _engine_mngr.ResetToDefaultMapping();
00314 _house_mngr.ResetMapping();
00315 _industry_mngr.ResetMapping();
00316 _industile_mngr.ResetMapping();
00317 }
00318
00319
00323 static void ShutdownGame()
00324 {
00325 IConsoleFree();
00326
00327 if (_network_available) NetworkShutDown();
00328
00329 DriverFactoryBase::ShutdownDrivers();
00330
00331 UnInitWindowSystem();
00332
00333
00334 AI::Uninitialize(false);
00335
00336
00337 UnInitializeAirports();
00338
00339
00340 GamelogReset();
00341 _town_pool.CleanPool();
00342 _industry_pool.CleanPool();
00343 _station_pool.CleanPool();
00344 _roadstop_pool.CleanPool();
00345 _vehicle_pool.CleanPool();
00346 _sign_pool.CleanPool();
00347 _order_pool.CleanPool();
00348 _group_pool.CleanPool();
00349 _cargopacket_pool.CleanPool();
00350 _engine_pool.CleanPool();
00351 _company_pool.CleanPool();
00352
00353 free(_config_file);
00354
00355
00356 FioCloseAll();
00357 }
00358
00359 static void LoadIntroGame()
00360 {
00361 _game_mode = GM_MENU;
00362
00363 ResetGRFConfig(false);
00364
00365
00366 ResetWindowSystem();
00367 SetupColoursAndInitialWindow();
00368
00369
00370 if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
00371 GenerateWorld(GWM_EMPTY, 64, 64);
00372 WaitTillGeneratedWorld();
00373 SetLocalCompany(COMPANY_SPECTATOR);
00374 } else {
00375 SetLocalCompany(COMPANY_FIRST);
00376 }
00377
00378 _pause_mode = PM_UNPAUSED;
00379 _cursor.fix_at = false;
00380
00381 CheckForMissingGlyphsInLoadedLanguagePack();
00382
00383
00384 if (_music_driver->IsSongPlaying()) ResetMusic();
00385 }
00386
00387 void MakeNewgameSettingsLive()
00388 {
00389 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00390 if (_settings_game.ai_config[c] != NULL) {
00391 delete _settings_game.ai_config[c];
00392 }
00393 }
00394
00395 _settings_game = _settings_newgame;
00396
00397 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00398 _settings_game.ai_config[c] = NULL;
00399 if (_settings_newgame.ai_config[c] != NULL) {
00400 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
00401 }
00402 }
00403 }
00404
00405 byte _savegame_sort_order;
00406 #if defined(UNIX) && !defined(__MORPHOS__)
00407 extern void DedicatedFork();
00408 #endif
00409
00410 int ttd_main(int argc, char *argv[])
00411 {
00412 int i;
00413 const char *optformat;
00414 char *musicdriver = NULL;
00415 char *sounddriver = NULL;
00416 char *videodriver = NULL;
00417 char *blitter = NULL;
00418 char *graphics_set = NULL;
00419 char *sounds_set = NULL;
00420 char *music_set = NULL;
00421 Dimension resolution = {0, 0};
00422 Year startyear = INVALID_YEAR;
00423 uint generation_seed = GENERATE_NEW_SEED;
00424 bool save_config = true;
00425 #if defined(ENABLE_NETWORK)
00426 bool dedicated = false;
00427 bool network = false;
00428 char *network_conn = NULL;
00429 char *debuglog_conn = NULL;
00430 char *dedicated_host = NULL;
00431 uint16 dedicated_port = 0;
00432 char *join_server_password = NULL;
00433 char *join_company_password = NULL;
00434 #endif
00435
00436 _game_mode = GM_MENU;
00437 _switch_mode = SM_MENU;
00438 _switch_mode_errorstr = INVALID_STRING_ID;
00439 _dedicated_forks = false;
00440 _config_file = NULL;
00441
00442
00443
00444
00445
00446 optformat = "m:s:v:b:hD::n::ei::I:S:t:d::r:g::G:c:xl:p:P:"
00447 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00448 "f"
00449 #endif
00450 ;
00451
00452 MyGetOptData mgo(argc - 1, argv + 1, optformat);
00453
00454 while ((i = MyGetOpt(&mgo)) != -1) {
00455 switch (i) {
00456 case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
00457 case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
00458 case 'M': free(music_set); music_set = strdup(mgo.opt); break;
00459 case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
00460 case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
00461 case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
00462 case 'b': free(blitter); blitter = strdup(mgo.opt); break;
00463 #if defined(ENABLE_NETWORK)
00464 case 'D':
00465 free(musicdriver);
00466 free(sounddriver);
00467 free(videodriver);
00468 free(blitter);
00469 musicdriver = strdup("null");
00470 sounddriver = strdup("null");
00471 videodriver = strdup("dedicated");
00472 blitter = strdup("null");
00473 dedicated = true;
00474 SetDebugString("net=6");
00475 if (mgo.opt != NULL) {
00476
00477
00478 const char *temp = NULL;
00479 const char *port = NULL;
00480 ParseConnectionString(&temp, &port, mgo.opt);
00481 if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
00482 if (port != NULL) dedicated_port = atoi(port);
00483 }
00484 break;
00485 case 'f': _dedicated_forks = true; break;
00486 case 'n':
00487 network = true;
00488 network_conn = mgo.opt;
00489 break;
00490 case 'l':
00491 debuglog_conn = mgo.opt;
00492 break;
00493 case 'p':
00494 join_server_password = mgo.opt;
00495 break;
00496 case 'P':
00497 join_company_password = mgo.opt;
00498 break;
00499 #endif
00500 case 'r': ParseResolution(&resolution, mgo.opt); break;
00501 case 't': startyear = atoi(mgo.opt); break;
00502 case 'd': {
00503 #if defined(WIN32)
00504 CreateConsole();
00505 #endif
00506 if (mgo.opt != NULL) SetDebugString(mgo.opt);
00507 } break;
00508 case 'e': _switch_mode = SM_EDITOR; break;
00509 case 'i':
00510
00511 if (!StrEmpty(mgo.opt) && mgo.opt[1] == '\0') {
00512 _use_palette = (PaletteType)(mgo.opt[0] - '0');
00513 if (_use_palette <= MAX_PAL) break;
00514 }
00515 usererror("Valid value for '-i' is 0, 1 or 2");
00516 case 'g':
00517 if (mgo.opt != NULL) {
00518 strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
00519 _switch_mode = SM_LOAD;
00520 _file_to_saveload.mode = SL_LOAD;
00521
00522
00523 const char *t = strrchr(_file_to_saveload.name, '.');
00524 if (t != NULL) {
00525 FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
00526 if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
00527 }
00528
00529 break;
00530 }
00531
00532 _switch_mode = SM_NEWGAME;
00533
00534 if (generation_seed == GENERATE_NEW_SEED) {
00535 generation_seed = InteractiveRandom();
00536 }
00537 break;
00538 case 'G': generation_seed = atoi(mgo.opt); break;
00539 case 'c': _config_file = strdup(mgo.opt); break;
00540 case 'x': save_config = false; break;
00541 case -2:
00542 case 'h':
00543
00544
00545
00546 DeterminePaths(argv[0]);
00547 BaseGraphics::FindSets();
00548 BaseSounds::FindSets();
00549 BaseMusic::FindSets();
00550 ShowHelp();
00551 return 0;
00552 }
00553 }
00554
00555 #if defined(WINCE) && defined(_DEBUG)
00556
00557 SetDebugString("4");
00558 #endif
00559
00560 DeterminePaths(argv[0]);
00561 BaseGraphics::FindSets();
00562 BaseSounds::FindSets();
00563 BaseMusic::FindSets();
00564
00565 #if defined(UNIX) && !defined(__MORPHOS__)
00566
00567 if (_dedicated_forks)
00568 DedicatedFork();
00569 #endif
00570
00571 AI::Initialize();
00572 LoadFromConfig();
00573 AI::Uninitialize(true);
00574 CheckConfig();
00575 LoadFromHighScore();
00576
00577 if (resolution.width != 0) { _cur_resolution = resolution; }
00578 if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
00579 if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
00580
00581
00582
00583
00584
00585
00586 _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX);
00587 _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX);
00588
00589 #if defined(ENABLE_NETWORK)
00590 if (dedicated_host) {
00591 _network_bind_list.Clear();
00592 *_network_bind_list.Append() = strdup(dedicated_host);
00593 }
00594 if (dedicated_port) _settings_client.network.server_port = dedicated_port;
00595 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
00596 #endif
00597
00598
00599 InitializeLanguagePacks();
00600
00601
00602 InitializeScreenshotFormats();
00603
00604
00605 InitializeAirports();
00606
00607
00608 InitializeDynamicVariables();
00609
00610
00611 InitFreeType();
00612
00613
00614 InitWindowSystem();
00615
00616
00617
00618
00619 if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
00620 if (!BaseSounds::SetSet(sounds_set)) {
00621 StrEmpty(sounds_set) ?
00622 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.") :
00623 usererror("Failed to select requested sounds set '%s'", sounds_set);
00624 }
00625 free(sounds_set);
00626
00627 if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
00628 if (!BaseGraphics::SetSet(graphics_set)) {
00629 StrEmpty(graphics_set) ?
00630 usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD. See section 4.1 of readme.txt.") :
00631 usererror("Failed to select requested graphics set '%s'", graphics_set);
00632 }
00633 free(graphics_set);
00634
00635 if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
00636 if (!BaseMusic::SetSet(music_set)) {
00637 StrEmpty(music_set) ?
00638 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.") :
00639 usererror("Failed to select requested music set '%s'", music_set);
00640 }
00641 free(music_set);
00642
00643
00644 GfxInitPalettes();
00645
00646 DEBUG(misc, 1, "Loading blitter...");
00647 if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
00648 if (BlitterFactoryBase::SelectBlitter(blitter) == NULL)
00649 StrEmpty(blitter) ?
00650 usererror("Failed to autoprobe blitter") :
00651 usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
00652 free(blitter);
00653
00654 DEBUG(driver, 1, "Loading drivers...");
00655
00656 if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
00657 _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
00658 if (_sound_driver == NULL) {
00659 StrEmpty(sounddriver) ?
00660 usererror("Failed to autoprobe sound driver") :
00661 usererror("Failed to select requested sound driver '%s'", sounddriver);
00662 }
00663 free(sounddriver);
00664
00665 if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
00666 _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
00667 if (_video_driver == NULL) {
00668 StrEmpty(videodriver) ?
00669 usererror("Failed to autoprobe video driver") :
00670 usererror("Failed to select requested video driver '%s'", videodriver);
00671 }
00672 free(videodriver);
00673
00674 if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
00675 _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
00676 if (_music_driver == NULL) {
00677 StrEmpty(musicdriver) ?
00678 usererror("Failed to autoprobe music driver") :
00679 usererror("Failed to select requested music driver '%s'", musicdriver);
00680 }
00681 free(musicdriver);
00682
00683 _savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
00684
00685 _screen.zoom = ZOOM_LVL_NORMAL;
00686
00687
00688 _music_driver->SetVolume(msf.music_vol);
00689
00690 NetworkStartUp();
00691
00692 #if defined(ENABLE_NETWORK)
00693 if (debuglog_conn != NULL && _network_available) {
00694 const char *not_used = NULL;
00695 const char *port = NULL;
00696 uint16 rport;
00697
00698 rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
00699
00700 ParseConnectionString(¬_used, &port, debuglog_conn);
00701 if (port != NULL) rport = atoi(port);
00702
00703 NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
00704 }
00705 #endif
00706
00707 ScanNewGRFFiles();
00708
00709 ResetGRFConfig(false);
00710
00711
00712 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
00713
00714
00715 IConsoleInit();
00716 _cursor.in_window = true;
00717 InitializeGUI();
00718 IConsoleCmdExec("exec scripts/autoexec.scr 0");
00719
00720
00721 _genworld_paint_mutex->BeginCritical();
00722 _genworld_mapgen_mutex->BeginCritical();
00723
00724 GenerateWorld(GWM_EMPTY, 64, 64);
00725 WaitTillGeneratedWorld();
00726
00727 CheckForMissingGlyphsInLoadedLanguagePack();
00728
00729 #ifdef ENABLE_NETWORK
00730 if (network && _network_available) {
00731 if (network_conn != NULL) {
00732 const char *port = NULL;
00733 const char *company = NULL;
00734 uint16 rport = NETWORK_DEFAULT_PORT;
00735 CompanyID join_as = COMPANY_NEW_COMPANY;
00736
00737 ParseConnectionString(&company, &port, network_conn);
00738
00739 if (company != NULL) {
00740 join_as = (CompanyID)atoi(company);
00741
00742 if (join_as != COMPANY_SPECTATOR) {
00743 join_as--;
00744 if (join_as >= MAX_COMPANIES) return false;
00745 }
00746 }
00747 if (port != NULL) rport = atoi(port);
00748
00749 LoadIntroGame();
00750 _switch_mode = SM_NONE;
00751 NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
00752 }
00753 }
00754 #endif
00755
00756 _video_driver->MainLoop();
00757
00758 WaitTillSaved();
00759
00760
00761 if (save_config) {
00762 SaveToConfig();
00763 SaveToHighScore();
00764 }
00765
00766
00767 ShutdownGame();
00768
00769 free(const_cast<char *>(BaseGraphics::ini_set));
00770 free(const_cast<char *>(BaseSounds::ini_set));
00771 free(const_cast<char *>(BaseMusic::ini_set));
00772 free(_ini_musicdriver);
00773 free(_ini_sounddriver);
00774 free(_ini_videodriver);
00775 free(_ini_blitter);
00776
00777 return 0;
00778 }
00779
00780 void HandleExitGameRequest()
00781 {
00782 if (_game_mode == GM_MENU) {
00783 _exit_game = true;
00784 } else if (_settings_client.gui.autosave_on_exit) {
00785 DoExitSave();
00786 _exit_game = true;
00787 } else {
00788 AskExitGame();
00789 }
00790 }
00791
00792 static void MakeNewGameDone()
00793 {
00794 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
00795
00796
00797 if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0) {
00798 SetLocalCompany(COMPANY_SPECTATOR);
00799 IConsoleCmdExec("exec scripts/game_start.scr 0");
00800 return;
00801 }
00802
00803
00804 DoStartupNewCompany(false);
00805
00806 Company *c = Company::Get(COMPANY_FIRST);
00807 c->settings = _settings_client.company;
00808
00809 IConsoleCmdExec("exec scripts/game_start.scr 0");
00810
00811 SetLocalCompany(COMPANY_FIRST);
00812 _current_company = _local_company;
00813
00814 InitializeRailGUI();
00815
00816 #ifdef ENABLE_NETWORK
00817
00818
00819 if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00820 char *password = _settings_client.network.default_company_pass;
00821 NetworkChangeCompanyPassword(1, &password);
00822 }
00823 #endif
00824
00825 MarkWholeScreenDirty();
00826 }
00827
00828 static void MakeNewGame(bool from_heightmap, bool reset_settings)
00829 {
00830 _game_mode = GM_NORMAL;
00831
00832 ResetGRFConfig(true);
00833 InitializeDynamicVariables();
00834
00835 GenerateWorldSetCallback(&MakeNewGameDone);
00836 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
00837 }
00838
00839 static void MakeNewEditorWorldDone()
00840 {
00841 SetLocalCompany(OWNER_NONE);
00842 }
00843
00844 static void MakeNewEditorWorld()
00845 {
00846 _game_mode = GM_EDITOR;
00847
00848 ResetGRFConfig(true);
00849
00850 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00851 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00852 }
00853
00854 void StartupCompanies();
00855 void StartupDisasters();
00856 extern void StartupEconomy();
00857
00863 static void StartScenario()
00864 {
00865 _game_mode = GM_NORMAL;
00866
00867
00868 if (_file_to_saveload.mode == SL_INVALID) {
00869 DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
00870 SetDParamStr(0, GetSaveLoadErrorString());
00871 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, 0, 0);
00872 _game_mode = GM_MENU;
00873 return;
00874 }
00875
00876
00877 ResetWindowSystem();
00878
00879 SetupColoursAndInitialWindow();
00880
00881 ResetGRFConfig(true);
00882
00883
00884 if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, SCENARIO_DIR) != SL_OK) {
00885 LoadIntroGame();
00886 SetDParamStr(0, GetSaveLoadErrorString());
00887 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, 0, 0);
00888 }
00889
00890 _settings_game.difficulty = _settings_newgame.difficulty;
00891
00892
00893 StartupEconomy();
00894 StartupCompanies();
00895 StartupEngines();
00896 StartupDisasters();
00897
00898 SetLocalCompany(COMPANY_FIRST);
00899 _current_company = _local_company;
00900 Company *c = Company::Get(COMPANY_FIRST);
00901 c->settings = _settings_client.company;
00902
00903 MarkWholeScreenDirty();
00904 }
00905
00914 bool SafeSaveOrLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir)
00915 {
00916 GameMode ogm = _game_mode;
00917
00918 _game_mode = newgm;
00919 assert(mode == SL_LOAD || mode == SL_OLD_LOAD);
00920 switch (SaveOrLoad(filename, mode, subdir)) {
00921 case SL_OK: return true;
00922
00923 case SL_REINIT:
00924 switch (ogm) {
00925 default:
00926 case GM_MENU: LoadIntroGame(); break;
00927 case GM_EDITOR: MakeNewEditorWorld(); break;
00928 }
00929 return false;
00930
00931 default:
00932 _game_mode = ogm;
00933 return false;
00934 }
00935 }
00936
00937 void SwitchToMode(SwitchMode new_mode)
00938 {
00939 #ifdef ENABLE_NETWORK
00940
00941 if (new_mode != SM_SAVE) {
00942
00943 if (_networking) {
00944 if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
00945 NetworkReboot();
00946 } else {
00947 NetworkDisconnect();
00948 }
00949 }
00950
00951
00952 if (_is_network_server) {
00953
00954 if (new_mode != SM_MENU) {
00955
00956 if (_settings_client.network.reload_cfg) {
00957 LoadFromConfig();
00958 MakeNewgameSettingsLive();
00959 ResetGRFConfig(false);
00960 }
00961 NetworkServerStart();
00962 } else {
00963
00964 _is_network_server = false;
00965 }
00966 }
00967 }
00968 #endif
00969
00970 if (new_mode != SM_SAVE) AI::KillAll();
00971
00972 switch (new_mode) {
00973 case SM_EDITOR:
00974 MakeNewEditorWorld();
00975 break;
00976
00977 case SM_RESTARTGAME:
00978 case SM_NEWGAME:
00979 #ifdef ENABLE_NETWORK
00980 if (_network_server) {
00981 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
00982 }
00983 #endif
00984 MakeNewGame(false, new_mode == SM_NEWGAME);
00985 break;
00986
00987 case SM_START_SCENARIO:
00988 #ifdef ENABLE_NETWORK
00989 if (_network_server) {
00990 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded scenario)", _file_to_saveload.title);
00991 }
00992 #endif
00993 StartScenario();
00994 break;
00995
00996 case SM_LOAD: {
00997 ResetGRFConfig(true);
00998 ResetWindowSystem();
00999
01000 if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
01001 LoadIntroGame();
01002 SetDParamStr(0, GetSaveLoadErrorString());
01003 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, 0, 0);
01004 } else {
01005 if (_saveload_mode == SLD_LOAD_SCENARIO) {
01006 StartupEngines();
01007 }
01008
01009
01010 SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
01011
01012 IConsoleCmdExec("exec scripts/game_start.scr 0");
01013
01014 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01015 #ifdef ENABLE_NETWORK
01016 if (_network_server) {
01017 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
01018 }
01019 #endif
01020 }
01021 break;
01022 }
01023
01024 case SM_START_HEIGHTMAP:
01025 #ifdef ENABLE_NETWORK
01026 if (_network_server) {
01027 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
01028 }
01029 #endif
01030 MakeNewGame(true, true);
01031 break;
01032
01033 case SM_LOAD_HEIGHTMAP:
01034 SetLocalCompany(OWNER_NONE);
01035
01036 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01037 MarkWholeScreenDirty();
01038 break;
01039
01040 case SM_LOAD_SCENARIO: {
01041 if (SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
01042 SetLocalCompany(OWNER_NONE);
01043 _settings_newgame.game_creation.starting_year = _cur_year;
01044
01045 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01046 } else {
01047 SetDParamStr(0, GetSaveLoadErrorString());
01048 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, 0, 0);
01049 }
01050 break;
01051 }
01052
01053 case SM_MENU:
01054 LoadIntroGame();
01055 break;
01056
01057 case SM_SAVE:
01058
01059 if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
01060 SetDParamStr(0, GetSaveLoadErrorString());
01061 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, 0, 0);
01062 } else {
01063 DeleteWindowById(WC_SAVELOAD, 0);
01064 }
01065 break;
01066
01067 case SM_GENRANDLAND:
01068 SetLocalCompany(OWNER_NONE);
01069 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01070
01071 MarkWholeScreenDirty();
01072 break;
01073
01074 default: NOT_REACHED();
01075 }
01076
01077 if (_switch_mode_errorstr != INVALID_STRING_ID) {
01078 ShowErrorMessage(_switch_mode_errorstr, INVALID_STRING_ID, 0, 0, true);
01079 }
01080 }
01081
01082
01088 void StateGameLoop()
01089 {
01090
01091 if (_pause_mode != PM_UNPAUSED) {
01092 CallWindowTickEvent();
01093 return;
01094 }
01095 if (IsGeneratingWorld()) return;
01096
01097 ClearStorageChanges(false);
01098
01099 if (_game_mode == GM_EDITOR) {
01100 RunTileLoop();
01101 CallVehicleTicks();
01102 CallLandscapeTick();
01103 ClearStorageChanges(true);
01104
01105 CallWindowTickEvent();
01106 NewsLoop();
01107 } else {
01108
01109 const RoadStop *rs;
01110 FOR_ALL_ROADSTOPS(rs) {
01111 if (IsStandardRoadStopTile(rs->xy)) continue;
01112
01113 assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
01114 rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
01115 rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
01116 }
01117
01118 if (_debug_desync_level > 1) {
01119 Vehicle *v;
01120 FOR_ALL_VEHICLES(v) {
01121 if (v != v->First()) continue;
01122
01123 switch (v->type) {
01124 case VEH_ROAD: {
01125 RoadVehicle *rv = RoadVehicle::From(v);
01126 RoadVehicleCache cache = rv->rcache;
01127 RoadVehUpdateCache(rv);
01128
01129 if (memcmp(&cache, &rv->rcache, sizeof(RoadVehicleCache)) != 0) {
01130 DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
01131 }
01132 } break;
01133
01134 case VEH_TRAIN: {
01135 uint length = 0;
01136 Train *t = Train::From(v);
01137 for (Vehicle *u = t; u != NULL; u = u->Next()) length++;
01138
01139 TrainCache *wagons = MallocT<TrainCache>(length);
01140 length = 0;
01141 for (Train *u = t; u != NULL; u = u->Next()) wagons[length++] = u->tcache;
01142
01143 t->ConsistChanged(true);
01144
01145 length = 0;
01146 for (Train *u = t; u != NULL; u = u->Next()) {
01147 if (memcmp(&wagons[length], &u->tcache, sizeof(TrainCache)) != 0) {
01148 DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i, wagon %i\n", v->index, (int)v->owner, v->unitnumber, length);
01149 }
01150 length++;
01151 }
01152
01153 free(wagons);
01154 } break;
01155
01156 case VEH_AIRCRAFT: {
01157 Aircraft *a = Aircraft::From(v);
01158 AircraftCache cache = a->acache;
01159 UpdateAircraftCache(a);
01160
01161 if (memcmp(&cache, &a->acache, sizeof(AircraftCache)) != 0) {
01162 DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
01163 }
01164 } break;
01165
01166 default:
01167 break;
01168 }
01169 }
01170 }
01171
01172
01173 Vehicle *v;
01174 FOR_ALL_VEHICLES(v) {
01175 byte buff[sizeof(VehicleCargoList)];
01176 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
01177 v->cargo.InvalidateCache();
01178 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
01179 }
01180
01181 Station *st;
01182 FOR_ALL_STATIONS(st) {
01183 for (CargoID c = 0; c < NUM_CARGO; c++) {
01184 byte buff[sizeof(StationCargoList)];
01185 memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
01186 st->goods[c].cargo.InvalidateCache();
01187 assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
01188 }
01189 }
01190
01191
01192
01193 CompanyID old_company = _current_company;
01194 _current_company = OWNER_NONE;
01195
01196 AnimateAnimatedTiles();
01197 IncreaseDate();
01198 RunTileLoop();
01199 CallVehicleTicks();
01200 CallLandscapeTick();
01201 ClearStorageChanges(true);
01202
01203 AI::GameLoop();
01204
01205 CallWindowTickEvent();
01206 NewsLoop();
01207 _current_company = old_company;
01208 }
01209 }
01210
01213 static void DoAutosave()
01214 {
01215 char buf[MAX_PATH];
01216
01217 #if defined(PSP)
01218
01219 if (_networking) return;
01220 #endif
01221
01222 if (_settings_client.gui.keep_all_autosave) {
01223 GenerateDefaultSaveName(buf, lastof(buf));
01224 strecat(buf, ".sav", lastof(buf));
01225 } else {
01226 static int _autosave_ctr = 0;
01227
01228
01229 snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01230
01231 if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01232 }
01233
01234 DEBUG(sl, 2, "Autosaving to '%s'", buf);
01235 if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01236 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, 0, 0);
01237 }
01238 }
01239
01240 void GameLoop()
01241 {
01242 ProcessAsyncSaveFinish();
01243
01244
01245 if (_do_autosave) {
01246 _do_autosave = false;
01247 DoAutosave();
01248 RedrawAutosave();
01249 }
01250
01251
01252 if (_switch_mode != SM_NONE) {
01253 SwitchToMode(_switch_mode);
01254 _switch_mode = SM_NONE;
01255 }
01256
01257 IncreaseSpriteLRU();
01258 InteractiveRandom();
01259
01260 extern int _caret_timer;
01261 _caret_timer += 3;
01262 _palette_animation_counter += 8;
01263 CursorTick();
01264
01265 #ifdef ENABLE_NETWORK
01266
01267 if (_network_available) NetworkUDPGameLoop();
01268
01269 if (_networking && !IsGeneratingWorld()) {
01270
01271 NetworkGameLoop();
01272 } else {
01273 if (_network_reconnect > 0 && --_network_reconnect == 0) {
01274
01275
01276 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
01277 }
01278
01279 StateGameLoop();
01280 }
01281 #else
01282 StateGameLoop();
01283 #endif
01284
01285 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01286
01287 if (!_pause_mode || _cheats.build_in_pause.value) MoveAllTextEffects();
01288
01289 InputLoop();
01290
01291 _sound_driver->MainLoop();
01292 MusicLoop();
01293 }