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