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