00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "stdafx.h"
00013
00014 #include "blitter/factory.hpp"
00015 #include "sound/sound_driver.hpp"
00016 #include "music/music_driver.hpp"
00017 #include "video/video_driver.hpp"
00018
00019 #include "fontcache.h"
00020 #include "error.h"
00021 #include "gui.h"
00022 #include "sound_func.h"
00023 #include "window_func.h"
00024
00025 #include "base_media_base.h"
00026 #include "saveload/saveload.h"
00027 #include "company_func.h"
00028 #include "command_func.h"
00029 #include "news_func.h"
00030 #include "fios.h"
00031 #include "aircraft.h"
00032 #include "roadveh.h"
00033 #include "train.h"
00034 #include "ship.h"
00035 #include "console_func.h"
00036 #include "screenshot.h"
00037 #include "network/network.h"
00038 #include "network/network_func.h"
00039 #include "signs_base.h"
00040 #include "ai/ai.hpp"
00041 #include "ai/ai_config.hpp"
00042 #include "settings_func.h"
00043 #include "genworld.h"
00044 #include "progress.h"
00045 #include "group.h"
00046 #include "strings_func.h"
00047 #include "date_func.h"
00048 #include "vehicle_func.h"
00049 #include "gamelog.h"
00050 #include "animated_tile_func.h"
00051 #include "roadstop_base.h"
00052 #include "elrail_func.h"
00053 #include "rev.h"
00054 #include "highscore.h"
00055 #include "thread/thread.h"
00056 #include "station_base.h"
00057 #include "crashlog.h"
00058 #include "engine_func.h"
00059 #include "core/random_func.hpp"
00060 #include "rail_gui.h"
00061 #include "core/backup_type.hpp"
00062 #include "hotkeys.h"
00063 #include "newgrf.h"
00064 #include "misc/getoptdata.h"
00065
00066
00067 #include "town.h"
00068 #include "industry.h"
00069
00070 #include "linkgraph/linkgraph.h"
00071
00072 #include <stdarg.h>
00073
00074 #include "table/strings.h"
00075
00076 void CallLandscapeTick();
00077 void IncreaseDate();
00078 void DoPaletteAnimations();
00079 void MusicLoop();
00080 void ResetMusic();
00081 void CallWindowTickEvent();
00082 bool HandleBootstrap();
00083
00084 extern void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
00085 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
00086 extern void ShowOSErrorBox(const char *buf, bool system);
00087 extern char *_config_file;
00088
00094 void CDECL usererror(const char *s, ...)
00095 {
00096 va_list va;
00097 char buf[512];
00098
00099 va_start(va, s);
00100 vsnprintf(buf, lengthof(buf), s, va);
00101 va_end(va);
00102
00103 ShowOSErrorBox(buf, false);
00104 if (_video_driver != NULL) _video_driver->Stop();
00105
00106 exit(1);
00107 }
00108
00114 void CDECL error(const char *s, ...)
00115 {
00116 va_list va;
00117 char buf[512];
00118
00119 va_start(va, s);
00120 vsnprintf(buf, lengthof(buf), s, va);
00121 va_end(va);
00122
00123 ShowOSErrorBox(buf, true);
00124
00125
00126 CrashLog::SetErrorMessage(buf);
00127 abort();
00128 }
00129
00134 void CDECL ShowInfoF(const char *str, ...)
00135 {
00136 va_list va;
00137 char buf[1024];
00138 va_start(va, str);
00139 vsnprintf(buf, lengthof(buf), str, va);
00140 va_end(va);
00141 ShowInfo(buf);
00142 }
00143
00147 static void ShowHelp()
00148 {
00149 char buf[8192];
00150 char *p = buf;
00151
00152 p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
00153 p = strecpy(p,
00154 "\n"
00155 "\n"
00156 "Command line options:\n"
00157 " -v drv = Set video driver (see below)\n"
00158 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
00159 " -m drv = Set music driver (see below)\n"
00160 " -b drv = Set the blitter to use (see below)\n"
00161 " -r res = Set resolution (for instance 800x600)\n"
00162 " -h = Display this help text\n"
00163 " -t year = Set starting year\n"
00164 " -d [[fac=]lvl[,...]]= Debug mode\n"
00165 " -e = Start Editor\n"
00166 " -g [savegame] = Start new/save game immediately\n"
00167 " -G seed = Set random seed\n"
00168 #if defined(ENABLE_NETWORK)
00169 " -n [ip:port#company]= Start networkgame\n"
00170 " -p password = Password to join server\n"
00171 " -P password = Password to join company\n"
00172 " -D [ip][:port] = Start dedicated server\n"
00173 " -l ip[:port] = Redirect DEBUG()\n"
00174 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00175 " -f = Fork into the background (dedicated only)\n"
00176 #endif
00177 #endif
00178 " -I graphics_set = Force the graphics set (see below)\n"
00179 " -S sounds_set = Force the sounds set (see below)\n"
00180 " -M music_set = Force the music set (see below)\n"
00181 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
00182 " -x = Do not automatically save to config file on exit\n"
00183 " -q savegame = Write some information about the savegame and exit\n"
00184 "\n",
00185 lastof(buf)
00186 );
00187
00188
00189 p = BaseGraphics::GetSetsList(p, lastof(buf));
00190
00191
00192 p = BaseSounds::GetSetsList(p, lastof(buf));
00193
00194
00195 p = BaseMusic::GetSetsList(p, lastof(buf));
00196
00197
00198 p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
00199
00200
00201 p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
00202
00203
00204 AI::Initialize();
00205 p = AI::GetConsoleList(p, lastof(buf), true);
00206 AI::Uninitialize(true);
00207
00208
00209
00210 #if !defined(WIN32) && !defined(WIN64)
00211 printf("%s\n", buf);
00212 #else
00213 ShowInfo(buf);
00214 #endif
00215 }
00216
00217 static void WriteSavegameInfo(const char *name)
00218 {
00219 extern uint16 _sl_version;
00220 uint32 last_ottd_rev = 0;
00221 byte ever_modified = 0;
00222 bool removed_newgrfs = false;
00223
00224 GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
00225
00226 char buf[8192];
00227 char *p = buf;
00228 p += seprintf(p, lastof(buf), "Name: %s\n", name);
00229 p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
00230 p += seprintf(p, lastof(buf), "NewGRF ver: 0x%08X\n", last_ottd_rev);
00231 p += seprintf(p, lastof(buf), "Modified: %d\n", ever_modified);
00232
00233 if (removed_newgrfs) {
00234 p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
00235 }
00236
00237 p = strecpy(p, "NewGRFs:\n", lastof(buf));
00238 if (_load_check_data.HasNewGrfs()) {
00239 for (GRFConfig *c = _load_check_data.grfconfig; c != NULL; c = c->next) {
00240 char md5sum[33];
00241 md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
00242 p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
00243 }
00244 }
00245
00246
00247
00248 #if !defined(WIN32) && !defined(WIN64)
00249 printf("%s\n", buf);
00250 #else
00251 ShowInfo(buf);
00252 #endif
00253 }
00254
00255
00262 static void ParseResolution(Dimension *res, const char *s)
00263 {
00264 const char *t = strchr(s, 'x');
00265 if (t == NULL) {
00266 ShowInfoF("Invalid resolution '%s'", s);
00267 return;
00268 }
00269
00270 res->width = max(strtoul(s, NULL, 0), 64UL);
00271 res->height = max(strtoul(t + 1, NULL, 0), 64UL);
00272 }
00273
00274
00279 static void ShutdownGame()
00280 {
00281 IConsoleFree();
00282
00283 if (_network_available) NetworkShutDown();
00284
00285 DriverFactoryBase::ShutdownDrivers();
00286
00287 UnInitWindowSystem();
00288
00289
00290 AI::Uninitialize(false);
00291
00292
00293 GamelogReset();
00294
00295
00296
00297
00298
00299 InitializeLinkGraphs();
00300
00301 #ifdef ENABLE_NETWORK
00302 free(_config_file);
00303 #endif
00304
00305 PoolBase::Clean(PT_ALL);
00306
00307
00308 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
00309
00310
00311 FioCloseAll();
00312
00313 UninitFreeType();
00314 }
00315
00320 static void LoadIntroGame(bool load_newgrfs = true)
00321 {
00322 _game_mode = GM_MENU;
00323
00324 if (load_newgrfs) ResetGRFConfig(false);
00325
00326
00327 ResetWindowSystem();
00328 SetupColoursAndInitialWindow();
00329
00330
00331 if (SaveOrLoad("opntitle.dat", SL_LOAD, BASESET_DIR) != SL_OK) {
00332 GenerateWorld(GWM_EMPTY, 64, 64);
00333 WaitTillGeneratedWorld();
00334 SetLocalCompany(COMPANY_SPECTATOR);
00335 } else {
00336 SetLocalCompany(COMPANY_FIRST);
00337 }
00338
00339 _pause_mode = PM_UNPAUSED;
00340 _cursor.fix_at = false;
00341
00342 CheckForMissingSprites();
00343 CheckForMissingGlyphs();
00344
00345
00346 if (_music_driver->IsSongPlaying()) ResetMusic();
00347 }
00348
00349 void MakeNewgameSettingsLive()
00350 {
00351 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00352 if (_settings_game.ai_config[c] != NULL) {
00353 delete _settings_game.ai_config[c];
00354 }
00355 }
00356
00357
00358
00359 _settings_game = _settings_newgame;
00360 _old_vds = _settings_client.company.vehicle;
00361
00362 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
00363 _settings_game.ai_config[c] = NULL;
00364 if (_settings_newgame.ai_config[c] != NULL) {
00365 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
00366 }
00367 }
00368 }
00369
00370 void OpenBrowser(const char *url)
00371 {
00372
00373 if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
00374
00375 extern void OSOpenBrowser(const char *url);
00376 OSOpenBrowser(url);
00377 }
00378
00380 struct AfterNewGRFScan : NewGRFScanCallback {
00381 Year startyear;
00382 uint generation_seed;
00383 char *dedicated_host;
00384 uint16 dedicated_port;
00385 char *network_conn;
00386 const char *join_server_password;
00387 const char *join_company_password;
00388 bool *save_config_ptr;
00389 bool save_config;
00390
00396 AfterNewGRFScan(bool *save_config_ptr) :
00397 startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
00398 dedicated_host(NULL), dedicated_port(0), network_conn(NULL),
00399 join_server_password(NULL), join_company_password(NULL),
00400 save_config_ptr(save_config_ptr), save_config(true)
00401 {
00402 }
00403
00404 virtual void OnNewGRFsScanned()
00405 {
00406 ResetGRFConfig(false);
00407
00408 TarScanner::DoScan(TarScanner::SCENARIO);
00409
00410 AI::Initialize();
00411
00412
00413 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
00414 LoadFromConfig();
00415 _settings_client.gui.last_newgrf_count = last_newgrf_count;
00416
00417
00418 UpdateNewGRFConfigPalette();
00419
00420 AI::Uninitialize(true);
00421 CheckConfig();
00422 LoadFromHighScore();
00423 LoadHotkeysFromConfig();
00424
00425
00426 *save_config_ptr = save_config;
00427
00428
00429 if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
00430 if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
00431
00432 #if defined(ENABLE_NETWORK)
00433 if (dedicated_host != NULL) {
00434 _network_bind_list.Clear();
00435 *_network_bind_list.Append() = strdup(dedicated_host);
00436 }
00437 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
00438 #endif
00439
00440
00441 IConsoleInit();
00442 InitializeGUI();
00443 IConsoleCmdExec("exec scripts/autoexec.scr 0");
00444
00445
00446 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
00447
00448 #ifdef ENABLE_NETWORK
00449 if (_network_available && network_conn != NULL) {
00450 const char *port = NULL;
00451 const char *company = NULL;
00452 uint16 rport = NETWORK_DEFAULT_PORT;
00453 CompanyID join_as = COMPANY_NEW_COMPANY;
00454
00455 ParseConnectionString(&company, &port, network_conn);
00456
00457 if (company != NULL) {
00458 join_as = (CompanyID)atoi(company);
00459
00460 if (join_as != COMPANY_SPECTATOR) {
00461 join_as--;
00462 if (join_as >= MAX_COMPANIES) {
00463 delete this;
00464 return;
00465 }
00466 }
00467 }
00468 if (port != NULL) rport = atoi(port);
00469
00470 LoadIntroGame();
00471 _switch_mode = SM_NONE;
00472 NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
00473 }
00474 #endif
00475
00476
00477 delete this;
00478 }
00479 };
00480
00481 #if defined(UNIX) && !defined(__MORPHOS__)
00482 extern void DedicatedFork();
00483 #endif
00484
00486 static const OptionData _options[] = {
00487 GETOPT_SHORT_VALUE('I'),
00488 GETOPT_SHORT_VALUE('S'),
00489 GETOPT_SHORT_VALUE('M'),
00490 GETOPT_SHORT_VALUE('m'),
00491 GETOPT_SHORT_VALUE('s'),
00492 GETOPT_SHORT_VALUE('v'),
00493 GETOPT_SHORT_VALUE('b'),
00494 #if defined(ENABLE_NETWORK)
00495 GETOPT_SHORT_OPTVAL('D'),
00496 GETOPT_SHORT_OPTVAL('n'),
00497 GETOPT_SHORT_VALUE('l'),
00498 GETOPT_SHORT_VALUE('p'),
00499 GETOPT_SHORT_VALUE('P'),
00500 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
00501 GETOPT_SHORT_NOVAL('f'),
00502 #endif
00503 #endif
00504 GETOPT_SHORT_VALUE('r'),
00505 GETOPT_SHORT_VALUE('t'),
00506 GETOPT_SHORT_OPTVAL('d'),
00507 GETOPT_SHORT_NOVAL('e'),
00508 GETOPT_SHORT_OPTVAL('g'),
00509 GETOPT_SHORT_VALUE('G'),
00510 GETOPT_SHORT_VALUE('c'),
00511 GETOPT_SHORT_NOVAL('x'),
00512 GETOPT_SHORT_VALUE('q'),
00513 GETOPT_SHORT_NOVAL('h'),
00514 GETOPT_END()
00515 };
00516
00517
00518 int ttd_main(int argc, char *argv[])
00519 {
00520 char *musicdriver = NULL;
00521 char *sounddriver = NULL;
00522 char *videodriver = NULL;
00523 char *blitter = NULL;
00524 char *graphics_set = NULL;
00525 char *sounds_set = NULL;
00526 char *music_set = NULL;
00527 Dimension resolution = {0, 0};
00528
00529 bool save_config = false;
00530 AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
00531 #if defined(ENABLE_NETWORK)
00532 bool dedicated = false;
00533 char *debuglog_conn = NULL;
00534
00535 extern bool _dedicated_forks;
00536 _dedicated_forks = false;
00537 #endif
00538
00539 _game_mode = GM_MENU;
00540 _switch_mode = SM_MENU;
00541 _config_file = NULL;
00542
00543 GetOptData mgo(argc - 1, argv + 1, _options);
00544
00545 int i;
00546 while ((i = mgo.GetOpt()) != -1) {
00547 switch (i) {
00548 case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
00549 case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
00550 case 'M': free(music_set); music_set = strdup(mgo.opt); break;
00551 case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
00552 case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
00553 case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
00554 case 'b': free(blitter); blitter = strdup(mgo.opt); break;
00555 #if defined(ENABLE_NETWORK)
00556 case 'D':
00557 free(musicdriver);
00558 free(sounddriver);
00559 free(videodriver);
00560 free(blitter);
00561 musicdriver = strdup("null");
00562 sounddriver = strdup("null");
00563 videodriver = strdup("dedicated");
00564 blitter = strdup("null");
00565 dedicated = true;
00566 SetDebugString("net=6");
00567 if (mgo.opt != NULL) {
00568
00569
00570 const char *temp = NULL;
00571 const char *port = NULL;
00572 ParseConnectionString(&temp, &port, mgo.opt);
00573 if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
00574 if (port != NULL) scanner->dedicated_port = atoi(port);
00575 }
00576 break;
00577 case 'f': _dedicated_forks = true; break;
00578 case 'n':
00579 scanner->network_conn = mgo.opt;
00580 break;
00581 case 'l':
00582 debuglog_conn = mgo.opt;
00583 break;
00584 case 'p':
00585 scanner->join_server_password = mgo.opt;
00586 break;
00587 case 'P':
00588 scanner->join_company_password = mgo.opt;
00589 break;
00590 #endif
00591 case 'r': ParseResolution(&resolution, mgo.opt); break;
00592 case 't': scanner->startyear = atoi(mgo.opt); break;
00593 case 'd': {
00594 #if defined(WIN32)
00595 CreateConsole();
00596 #endif
00597 if (mgo.opt != NULL) SetDebugString(mgo.opt);
00598 break;
00599 }
00600 case 'e': _switch_mode = SM_EDITOR; break;
00601 case 'g':
00602 if (mgo.opt != NULL) {
00603 strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
00604 _switch_mode = SM_LOAD_GAME;
00605 _file_to_saveload.mode = SL_LOAD;
00606
00607
00608 const char *t = strrchr(_file_to_saveload.name, '.');
00609 if (t != NULL) {
00610 FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
00611 if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
00612 }
00613
00614 break;
00615 }
00616
00617 _switch_mode = SM_NEWGAME;
00618
00619 if (scanner->generation_seed == GENERATE_NEW_SEED) {
00620 scanner->generation_seed = InteractiveRandom();
00621 }
00622 break;
00623 case 'q': {
00624 DeterminePaths(argv[0]);
00625 if (StrEmpty(mgo.opt)) return 1;
00626 char title[80];
00627 title[0] = '\0';
00628 FiosGetSavegameListCallback(SLD_LOAD_GAME, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
00629
00630 _load_check_data.Clear();
00631 SaveOrLoadResult res = SaveOrLoad(mgo.opt, SL_LOAD_CHECK, SAVE_DIR, false);
00632 if (res != SL_OK || _load_check_data.HasErrors()) {
00633 fprintf(stderr, "Failed to open savegame\n");
00634 if (_load_check_data.HasErrors()) {
00635 char buf[256];
00636 SetDParamStr(0, _load_check_data.error_data);
00637 GetString(buf, _load_check_data.error, lastof(buf));
00638 fprintf(stderr, "%s\n", buf);
00639 }
00640 return 1;
00641 }
00642
00643 WriteSavegameInfo(title);
00644
00645 return 0;
00646 }
00647 case 'G': scanner->generation_seed = atoi(mgo.opt); break;
00648 case 'c': _config_file = strdup(mgo.opt); break;
00649 case 'x': scanner->save_config = false; break;
00650 case 'h':
00651 i = -2;
00652 break;
00653 }
00654 if (i == -2) break;
00655 }
00656
00657 if (i == -2 || mgo.numleft > 0) {
00658
00659
00660
00661
00662
00663 DeterminePaths(argv[0]);
00664 TarScanner::DoScan(TarScanner::BASESET);
00665 BaseGraphics::FindSets();
00666 BaseSounds::FindSets();
00667 BaseMusic::FindSets();
00668 ShowHelp();
00669 delete scanner;
00670 return 0;
00671 }
00672
00673 #if defined(WINCE) && defined(_DEBUG)
00674
00675 SetDebugString("4");
00676 #endif
00677
00678 DeterminePaths(argv[0]);
00679 TarScanner::DoScan(TarScanner::BASESET);
00680
00681 #if defined(ENABLE_NETWORK)
00682 if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
00683 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
00684
00685 #if defined(UNIX) && !defined(__MORPHOS__)
00686
00687 if (_dedicated_forks) DedicatedFork();
00688 #endif
00689 #endif
00690
00691 LoadFromConfig(true);
00692
00693 if (resolution.width != 0) _cur_resolution = resolution;
00694
00695
00696
00697
00698
00699
00700
00701 _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX / 2);
00702 _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
00703
00704
00705
00706
00707
00708 _cursor.in_window = true;
00709
00710
00711 InitializeLanguagePacks();
00712
00713
00714 InitFreeType(false);
00715
00716
00717 InitWindowSystem();
00718
00719 BaseGraphics::FindSets();
00720 if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
00721 if (!BaseGraphics::SetSet(graphics_set) && !StrEmpty(graphics_set)) {
00722 usererror("Failed to select requested graphics set '%s'", graphics_set);
00723 }
00724 free(graphics_set);
00725
00726
00727 GfxInitPalettes();
00728
00729 DEBUG(misc, 1, "Loading blitter...");
00730 if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
00731 _blitter_autodetected = StrEmpty(blitter);
00732
00733 if (!_blitter_autodetected || BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP || BlitterFactoryBase::SelectBlitter("32bpp-anim") == NULL) {
00734 if (BlitterFactoryBase::SelectBlitter(blitter) == NULL) {
00735 StrEmpty(blitter) ?
00736 usererror("Failed to autoprobe blitter") :
00737 usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
00738 }
00739 }
00740 free(blitter);
00741
00742 if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
00743 _video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
00744 if (_video_driver == NULL) {
00745 StrEmpty(videodriver) ?
00746 usererror("Failed to autoprobe video driver") :
00747 usererror("Failed to select requested video driver '%s'", videodriver);
00748 }
00749 free(videodriver);
00750
00751
00752 _screen.zoom = ZOOM_LVL_NORMAL;
00753
00754 NetworkStartUp();
00755
00756 #if defined(ENABLE_NETWORK)
00757 if (debuglog_conn != NULL && _network_available) {
00758 const char *not_used = NULL;
00759 const char *port = NULL;
00760 uint16 rport;
00761
00762 rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
00763
00764 ParseConnectionString(¬_used, &port, debuglog_conn);
00765 if (port != NULL) rport = atoi(port);
00766
00767 NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
00768 }
00769 #endif
00770
00771 if (!HandleBootstrap()) goto exit;
00772
00773 _video_driver->ClaimMousePointer();
00774
00775
00776 InitializeScreenshotFormats();
00777
00778 BaseSounds::FindSets();
00779 if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
00780 if (!BaseSounds::SetSet(sounds_set)) {
00781 StrEmpty(sounds_set) ?
00782 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.") :
00783 usererror("Failed to select requested sounds set '%s'", sounds_set);
00784 }
00785 free(sounds_set);
00786
00787 BaseMusic::FindSets();
00788 if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
00789 if (!BaseMusic::SetSet(music_set)) {
00790 StrEmpty(music_set) ?
00791 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.") :
00792 usererror("Failed to select requested music set '%s'", music_set);
00793 }
00794 free(music_set);
00795
00796 if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
00797 _sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
00798 if (_sound_driver == NULL) {
00799 StrEmpty(sounddriver) ?
00800 usererror("Failed to autoprobe sound driver") :
00801 usererror("Failed to select requested sound driver '%s'", sounddriver);
00802 }
00803 free(sounddriver);
00804
00805 if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
00806 _music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
00807 if (_music_driver == NULL) {
00808 StrEmpty(musicdriver) ?
00809 usererror("Failed to autoprobe music driver") :
00810 usererror("Failed to select requested music driver '%s'", musicdriver);
00811 }
00812 free(musicdriver);
00813
00814
00815 _music_driver->SetVolume(_settings_client.music.music_vol);
00816
00817
00818 _modal_progress_paint_mutex->BeginCritical();
00819 _modal_progress_work_mutex->BeginCritical();
00820
00821 GenerateWorld(GWM_EMPTY, 64, 64);
00822 WaitTillGeneratedWorld();
00823
00824 LoadIntroGame(false);
00825
00826 CheckForMissingGlyphs();
00827
00828 ScanNewGRFFiles(scanner);
00829
00830 _video_driver->MainLoop();
00831
00832 WaitTillSaved();
00833
00834
00835 if (save_config) {
00836 SaveToConfig();
00837 SaveHotkeysToConfig();
00838 SaveToHighScore();
00839 }
00840
00841 exit:
00842
00843 ShutdownGame();
00844
00845 free(BaseGraphics::ini_set);
00846 free(BaseSounds::ini_set);
00847 free(BaseMusic::ini_set);
00848 free(_ini_musicdriver);
00849 free(_ini_sounddriver);
00850 free(_ini_videodriver);
00851 free(_ini_blitter);
00852
00853 return 0;
00854 }
00855
00856 void HandleExitGameRequest()
00857 {
00858 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) {
00859 _exit_game = true;
00860 } else if (_settings_client.gui.autosave_on_exit) {
00861 DoExitSave();
00862 _exit_game = true;
00863 } else {
00864 AskExitGame();
00865 }
00866 }
00867
00868 static void MakeNewGameDone()
00869 {
00870 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
00871
00872
00873 if (!_video_driver->HasGUI()) {
00874 SetLocalCompany(COMPANY_SPECTATOR);
00875 IConsoleCmdExec("exec scripts/game_start.scr 0");
00876 return;
00877 }
00878
00879
00880 DoStartupNewCompany(false);
00881
00882 Company *c = Company::Get(COMPANY_FIRST);
00883 c->settings = _settings_client.company;
00884
00885 IConsoleCmdExec("exec scripts/game_start.scr 0");
00886
00887 SetLocalCompany(COMPANY_FIRST);
00888
00889 InitializeRailGUI();
00890
00891 #ifdef ENABLE_NETWORK
00892
00893
00894 if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
00895 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
00896 }
00897 #endif
00898
00899 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
00900
00901 MarkWholeScreenDirty();
00902 }
00903
00904 static void MakeNewGame(bool from_heightmap, bool reset_settings)
00905 {
00906 _game_mode = GM_NORMAL;
00907
00908 ResetGRFConfig(true);
00909
00910 GenerateWorldSetCallback(&MakeNewGameDone);
00911 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
00912 }
00913
00914 static void MakeNewEditorWorldDone()
00915 {
00916 SetLocalCompany(OWNER_NONE);
00917 }
00918
00919 static void MakeNewEditorWorld()
00920 {
00921 _game_mode = GM_EDITOR;
00922
00923 ResetGRFConfig(true);
00924
00925 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
00926 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
00927 }
00928
00939 bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
00940 {
00941 assert(mode == SL_LOAD || (lf == NULL && mode == SL_OLD_LOAD));
00942 GameMode ogm = _game_mode;
00943
00944 _game_mode = newgm;
00945
00946 switch (lf == NULL ? SaveOrLoad(filename, mode, subdir) : LoadWithFilter(lf)) {
00947 case SL_OK: return true;
00948
00949 case SL_REINIT:
00950 #ifdef ENABLE_NETWORK
00951 if (_network_dedicated) {
00952
00953
00954
00955
00956
00957
00958 DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
00959 MakeNewGame(false, true);
00960 return false;
00961 }
00962 if (_network_server) {
00963
00964 NetworkDisconnect();
00965 }
00966 #endif
00967
00968 switch (ogm) {
00969 default:
00970 case GM_MENU: LoadIntroGame(); break;
00971 case GM_EDITOR: MakeNewEditorWorld(); break;
00972 }
00973 return false;
00974
00975 default:
00976 _game_mode = ogm;
00977 return false;
00978 }
00979 }
00980
00981 void SwitchToMode(SwitchMode new_mode)
00982 {
00983 #ifdef ENABLE_NETWORK
00984
00985 if (new_mode != SM_SAVE_GAME) {
00986
00987 if (_networking) {
00988 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
00989 NetworkReboot();
00990 } else {
00991 NetworkDisconnect();
00992 }
00993 }
00994
00995
00996 if (_is_network_server) {
00997
00998 if (new_mode != SM_MENU) {
00999
01000 if (_settings_client.network.reload_cfg) {
01001 LoadFromConfig();
01002 MakeNewgameSettingsLive();
01003 ResetGRFConfig(false);
01004 }
01005 NetworkServerStart();
01006 } else {
01007
01008 _is_network_server = false;
01009 }
01010 }
01011 }
01012 #endif
01013
01014 if (new_mode != SM_SAVE_GAME) AI::KillAll();
01015
01016 switch (new_mode) {
01017 case SM_EDITOR:
01018 MakeNewEditorWorld();
01019 break;
01020
01021 case SM_RESTARTGAME:
01022 case SM_NEWGAME:
01023 #ifdef ENABLE_NETWORK
01024 if (_network_server) {
01025 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
01026 }
01027 #endif
01028 MakeNewGame(false, new_mode == SM_NEWGAME);
01029 break;
01030
01031 case SM_LOAD_GAME: {
01032 ResetGRFConfig(true);
01033 ResetWindowSystem();
01034
01035 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
01036 SetDParamStr(0, GetSaveLoadErrorString());
01037 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01038 } else {
01039 if (_saveload_mode == SLD_LOAD_SCENARIO) {
01040 StartupEngines();
01041 }
01042
01043
01044 SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
01045
01046 IConsoleCmdExec("exec scripts/game_start.scr 0");
01047
01048 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01049 #ifdef ENABLE_NETWORK
01050 if (_network_server) {
01051 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
01052 }
01053 #endif
01054 }
01055 break;
01056 }
01057
01058 case SM_START_HEIGHTMAP:
01059 #ifdef ENABLE_NETWORK
01060 if (_network_server) {
01061 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
01062 }
01063 #endif
01064 MakeNewGame(true, true);
01065 break;
01066
01067 case SM_LOAD_HEIGHTMAP:
01068 SetLocalCompany(OWNER_NONE);
01069
01070 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01071 MarkWholeScreenDirty();
01072 break;
01073
01074 case SM_LOAD_SCENARIO: {
01075 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
01076 SetLocalCompany(OWNER_NONE);
01077 _settings_newgame.game_creation.starting_year = _cur_year;
01078
01079 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
01080 } else {
01081 SetDParamStr(0, GetSaveLoadErrorString());
01082 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01083 }
01084 break;
01085 }
01086
01087 case SM_MENU:
01088 LoadIntroGame();
01089 if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
01090 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
01091 BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name);
01092 }
01093 break;
01094
01095 case SM_SAVE_GAME:
01096
01097 if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
01098 SetDParamStr(0, GetSaveLoadErrorString());
01099 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
01100 } else {
01101 DeleteWindowById(WC_SAVELOAD, 0);
01102 }
01103 break;
01104
01105 case SM_SAVE_HEIGHTMAP:
01106 MakeHeightmapScreenshot(_file_to_saveload.name);
01107 DeleteWindowById(WC_SAVELOAD, 0);
01108 break;
01109
01110 case SM_GENRANDLAND:
01111 SetLocalCompany(OWNER_NONE);
01112 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
01113
01114 MarkWholeScreenDirty();
01115 break;
01116
01117 default: NOT_REACHED();
01118 }
01119 }
01120
01121
01128 static void CheckCaches()
01129 {
01130
01131 SmallVector<CompanyInfrastructure, 4> old_infrastructure;
01132 Company *c;
01133 FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
01134
01135 extern void AfterLoadCompanyStats();
01136 AfterLoadCompanyStats();
01137
01138 uint i = 0;
01139 FOR_ALL_COMPANIES(c) {
01140 if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
01141 DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
01142 }
01143 i++;
01144 }
01145
01146
01147
01148 if (_debug_desync_level <= 1) return;
01149
01150
01151 const RoadStop *rs;
01152 FOR_ALL_ROADSTOPS(rs) {
01153 if (IsStandardRoadStopTile(rs->xy)) continue;
01154
01155 assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
01156 rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
01157 rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
01158 }
01159
01160 Vehicle *v;
01161 FOR_ALL_VEHICLES(v) {
01162 extern void FillNewGRFVehicleCache(const Vehicle *v);
01163 if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
01164
01165 uint length = 0;
01166 for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
01167
01168 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
01169 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
01170 GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
01171 TrainCache *tra_cache = CallocT<TrainCache>(length);
01172
01173 length = 0;
01174 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01175 FillNewGRFVehicleCache(u);
01176 grf_cache[length] = u->grf_cache;
01177 veh_cache[length] = u->vcache;
01178 switch (u->type) {
01179 case VEH_TRAIN:
01180 gro_cache[length] = Train::From(u)->gcache;
01181 tra_cache[length] = Train::From(u)->tcache;
01182 break;
01183 case VEH_ROAD:
01184 gro_cache[length] = RoadVehicle::From(u)->gcache;
01185 break;
01186 default:
01187 break;
01188 }
01189 length++;
01190 }
01191
01192 switch (v->type) {
01193 case VEH_TRAIN: Train::From(v)->ConsistChanged(true); break;
01194 case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
01195 case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
01196 case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
01197 default: break;
01198 }
01199
01200 length = 0;
01201 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
01202 FillNewGRFVehicleCache(u);
01203 if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
01204 DEBUG(desync, 2, "newgrf cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
01205 }
01206 if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
01207 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);
01208 }
01209 switch (u->type) {
01210 case VEH_TRAIN:
01211 if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01212 DEBUG(desync, 2, "train ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01213 }
01214 if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
01215 DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01216 }
01217 break;
01218 case VEH_ROAD:
01219 if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
01220 DEBUG(desync, 2, "road vehicle ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
01221 }
01222 break;
01223 default:
01224 break;
01225 }
01226 length++;
01227 }
01228
01229 free(grf_cache);
01230 free(veh_cache);
01231 free(gro_cache);
01232 free(tra_cache);
01233 }
01234
01235
01236 FOR_ALL_VEHICLES(v) {
01237 byte buff[sizeof(VehicleCargoList)];
01238 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
01239 v->cargo.InvalidateCache();
01240 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
01241 }
01242
01243 Station *st;
01244 FOR_ALL_STATIONS(st) {
01245 for (CargoID c = 0; c < NUM_CARGO; c++) {
01246 byte buff[sizeof(StationCargoList)];
01247 memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
01248 st->goods[c].cargo.InvalidateCache();
01249 assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
01250 }
01251 }
01252 }
01253
01259 void StateGameLoop()
01260 {
01261
01262 if (_pause_mode != PM_UNPAUSED) {
01263 UpdateLandscapingLimits();
01264 CallWindowTickEvent();
01265 return;
01266 }
01267 if (HasModalProgress()) return;
01268
01269 ClearStorageChanges(false);
01270
01271 if (_game_mode == GM_EDITOR) {
01272 RunTileLoop();
01273 CallVehicleTicks();
01274 CallLandscapeTick();
01275 ClearStorageChanges(true);
01276 UpdateLandscapingLimits();
01277
01278 CallWindowTickEvent();
01279 NewsLoop();
01280 } else {
01281 if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
01282
01283 char name[MAX_PATH];
01284 snprintf(name, lengthof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
01285 SaveOrLoad(name, SL_SAVE, AUTOSAVE_DIR, false);
01286 }
01287
01288 CheckCaches();
01289
01290
01291
01292 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
01293
01294 AnimateAnimatedTiles();
01295 IncreaseDate();
01296 RunTileLoop();
01297 CallVehicleTicks();
01298 CallLandscapeTick();
01299 ClearStorageChanges(true);
01300
01301 AI::GameLoop();
01302 UpdateLandscapingLimits();
01303
01304 CallWindowTickEvent();
01305 NewsLoop();
01306 cur_company.Restore();
01307 }
01308
01309 assert(IsLocalCompany());
01310 }
01311
01316 static void DoAutosave()
01317 {
01318 char buf[MAX_PATH];
01319
01320 #if defined(PSP)
01321
01322 if (_networking) return;
01323 #endif
01324
01325 if (_settings_client.gui.keep_all_autosave) {
01326 GenerateDefaultSaveName(buf, lastof(buf));
01327 strecat(buf, ".sav", lastof(buf));
01328 } else {
01329 static int _autosave_ctr = 0;
01330
01331
01332 snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
01333
01334 if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
01335 }
01336
01337 DEBUG(sl, 2, "Autosaving to '%s'", buf);
01338 if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
01339 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
01340 }
01341 }
01342
01343 void GameLoop()
01344 {
01345 if (_game_mode == GM_BOOTSTRAP) {
01346 #ifdef ENABLE_NETWORK
01347
01348 if (_network_available) NetworkUDPGameLoop();
01349 #endif
01350 InputLoop();
01351 return;
01352 }
01353
01354 ProcessAsyncSaveFinish();
01355
01356
01357 if (_do_autosave) {
01358 _do_autosave = false;
01359 DoAutosave();
01360 SetWindowDirty(WC_STATUS_BAR, 0);
01361 }
01362
01363
01364 if (_switch_mode != SM_NONE && !HasModalProgress()) {
01365 SwitchToMode(_switch_mode);
01366 _switch_mode = SM_NONE;
01367 }
01368
01369 IncreaseSpriteLRU();
01370 InteractiveRandom();
01371
01372 extern int _caret_timer;
01373 _caret_timer += 3;
01374 CursorTick();
01375
01376 #ifdef ENABLE_NETWORK
01377
01378 if (_network_available) NetworkUDPGameLoop();
01379
01380 if (_networking && !HasModalProgress()) {
01381
01382 NetworkGameLoop();
01383 } else {
01384 if (_network_reconnect > 0 && --_network_reconnect == 0) {
01385
01386
01387 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
01388 }
01389
01390 StateGameLoop();
01391 }
01392
01393
01394 static uint check_message = 0;
01395 if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
01396 check_message = 0;
01397 NetworkChatMessageLoop();
01398 }
01399 #else
01400 StateGameLoop();
01401 #endif
01402
01403 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
01404
01405 if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
01406
01407 InputLoop();
01408
01409 _sound_driver->MainLoop();
01410 MusicLoop();
01411 }