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