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