Rearrange DriverSystem::select
[openttd/fttd.git] / src / openttd.cpp
blob2c7003041e6e77994f38dfeceb1ff5e718aaae84
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file openttd.cpp Functions related to starting OpenTTD. */
12 #include "stdafx.h"
14 #include "blitter/blitter.h"
15 #include "sound/sound_driver.hpp"
16 #include "music/music_driver.hpp"
17 #include "video/video_driver.hpp"
19 #include "font.h"
20 #include "error.h"
21 #include "string.h"
22 #include "gui.h"
24 #include "base_media_base.h"
25 #include "saveload/saveload.h"
26 #include "company_func.h"
27 #include "command_func.h"
28 #include "news_func.h"
29 #include "fios.h"
30 #include "aircraft.h"
31 #include "roadveh.h"
32 #include "train.h"
33 #include "ship.h"
34 #include "console_func.h"
35 #include "screenshot.h"
36 #include "network/network.h"
37 #include "network/network_func.h"
38 #include "ai/ai.hpp"
39 #include "ai/ai_config.hpp"
40 #include "settings_func.h"
41 #include "genworld.h"
42 #include "progress.h"
43 #include "strings_func.h"
44 #include "date_func.h"
45 #include "vehicle_func.h"
46 #include "gamelog.h"
47 #include "animated_tile_func.h"
48 #include "roadstop_base.h"
49 #include "elrail_func.h"
50 #include "rev.h"
51 #include "highscore.h"
52 #include "station_base.h"
53 #include "crashlog.h"
54 #include "engine_func.h"
55 #include "core/random_func.hpp"
56 #include "rail_gui.h"
57 #include "core/backup_type.hpp"
58 #include "hotkeys.h"
59 #include "newgrf.h"
60 #include "misc/getoptdata.h"
61 #include "game/game.hpp"
62 #include "game/game_config.hpp"
63 #include "town.h"
64 #include "subsidy_func.h"
65 #include "gfx_layout.h"
66 #include "industry.h"
68 #include "linkgraph/linkgraphschedule.h"
70 #include <stdarg.h>
72 void CallLandscapeTick();
73 void IncreaseDate();
74 void DoPaletteAnimations();
75 void MusicLoop();
76 void ResetMusic();
77 void CallWindowTickEvent();
78 bool HandleBootstrap();
80 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
81 extern void ShowOSErrorBox(const char *buf, bool system);
82 extern char *_config_file;
84 /**
85 * Error handling for fatal user errors.
86 * @param s the string to print.
87 * @note Does NEVER return.
89 void CDECL usererror(const char *s, ...)
91 va_list va;
92 char buf[512];
94 va_start(va, s);
95 bstrvfmt (buf, s, va);
96 va_end(va);
98 ShowOSErrorBox(buf, false);
99 if (VideoDriver::GetActiveDriver() != NULL) VideoDriver::GetActiveDriver()->Stop();
101 exit(1);
105 * Error handling for fatal non-user errors.
106 * @param s the string to print.
107 * @note Does NEVER return.
109 void CDECL error(const char *s, ...)
111 va_list va;
112 char buf[512];
114 va_start(va, s);
115 bstrvfmt (buf, s, va);
116 va_end(va);
118 ShowOSErrorBox(buf, true);
120 /* Set the error message for the crash log and then invoke it. */
121 CrashLog::SetErrorMessage(buf);
122 abort();
126 * Shows some information on the console/a popup box depending on the OS.
127 * @param str the text to show.
129 void CDECL ShowInfoF(const char *str, ...)
131 va_list va;
132 char buf[1024];
133 va_start(va, str);
134 bstrvfmt (buf, str, va);
135 va_end(va);
136 ShowInfo(buf);
140 * Show the help message when someone passed a wrong parameter.
142 static void ShowHelp()
144 sstring<8192> buf;
146 buf.fmt ("OpenTTD %s\n", _openttd_revision);
147 buf.append (
148 "\n"
149 "\n"
150 "Command line options:\n"
151 " -v drv = Set video driver (see below)\n"
152 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
153 " -m drv = Set music driver (see below)\n"
154 " -b drv = Set the blitter to use (see below)\n"
155 " -r res = Set resolution (for instance 800x600)\n"
156 " -h = Display this help text\n"
157 " -t year = Set starting year\n"
158 " -d [[fac=]lvl[,...]]= Debug mode\n"
159 " -e = Start Editor\n"
160 " -g [savegame] = Start new/save game immediately\n"
161 " -G seed = Set random seed\n"
162 #if defined(ENABLE_NETWORK)
163 " -n [ip:port#company]= Join network game\n"
164 " -p password = Password to join server\n"
165 " -P password = Password to join company\n"
166 " -D [ip][:port] = Start dedicated server\n"
167 " -l ip[:port] = Redirect DEBUG()\n"
168 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
169 " -f = Fork into the background (dedicated only)\n"
170 #endif
171 #endif /* ENABLE_NETWORK */
172 " -I graphics_set = Force the graphics set (see below)\n"
173 " -S sounds_set = Force the sounds set (see below)\n"
174 " -M music_set = Force the music set (see below)\n"
175 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
176 " -x = Do not automatically save to config file on exit\n"
177 " -q savegame = Write some information about the savegame and exit\n"
178 "\n"
181 /* List the graphics packs */
182 BaseGraphics::GetSetsList (&buf);
184 /* List the sounds packs */
185 BaseSounds::GetSetsList (&buf);
187 /* List the music packs */
188 BaseMusic::GetSetsList (&buf);
190 /* List the drivers */
191 MusicDriver::GetDriversInfo (&buf);
192 SoundDriver::GetDriversInfo (&buf);
193 VideoDriver::GetDriversInfo (&buf);
195 /* List the blitters */
196 Blitter::list (&buf);
198 /* List the debug facilities. */
199 DumpDebugFacilityNames (&buf);
201 /* We need to initialize the AI, so it finds the AIs */
202 AI::Initialize();
203 AI::GetConsoleList (&buf, true);
204 AI::Uninitialize(true);
206 /* We need to initialize the GameScript, so it finds the GSs */
207 Game::Initialize();
208 Game::GetConsoleList (&buf, true);
209 Game::Uninitialize(true);
211 /* ShowInfo put output to stderr, but version information should go
212 * to stdout; this is the only exception */
213 #if !defined(WIN32) && !defined(WIN64)
214 printf("%s\n", buf.c_str());
215 #else
216 ShowInfo(buf.c_str());
217 #endif
220 static void WriteSavegameInfo(const char *name)
222 uint32 last_ottd_rev = 0;
223 byte ever_modified = 0;
224 bool removed_newgrfs = false;
226 GamelogInfo(&_load_check_data.gamelog, &last_ottd_rev, &ever_modified, &removed_newgrfs);
228 sstring<8192> buf;
229 buf.append_fmt ("Name: %s\n", name);
230 buf.append_fmt ("Savegame ver: %c%d\n", _load_check_data.sl_version.type == SGT_FTTD ? 'F' : 'O', _load_check_data.sl_version.fttd.version);
231 buf.append_fmt ("NewGRF ver: 0x%08X\n", last_ottd_rev);
232 buf.append_fmt ("Modified: %d\n", ever_modified);
234 if (removed_newgrfs) {
235 buf.append ("NewGRFs have been removed\n");
238 buf.append ("NewGRFs:\n");
239 if (_load_check_data.HasNewGrfs()) {
240 for (GRFConfig *c = _load_check_data.grfconfig; c != NULL; c = c->next) {
241 char md5sum[33];
242 md5sumToString (md5sum, HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
243 buf.append_fmt ("%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
247 /* ShowInfo put output to stderr, but version information should go
248 * to stdout; this is the only exception */
249 #if !defined(WIN32) && !defined(WIN64)
250 printf("%s\n", buf.c_str());
251 #else
252 ShowInfo(buf.c_str());
253 #endif
258 * Extract the resolution from the given string and store
259 * it in the 'res' parameter.
260 * @param res variable to store the resolution in.
261 * @param s the string to decompose.
263 static void ParseResolution(Dimension *res, const char *s)
265 const char *t = strchr(s, 'x');
266 if (t == NULL) {
267 ShowInfoF("Invalid resolution '%s'", s);
268 return;
271 res->width = max(strtoul(s, NULL, 0), 64UL);
272 res->height = max(strtoul(t + 1, NULL, 0), 64UL);
277 * Unitializes drivers, frees allocated memory, cleans pools, ...
278 * Generally, prepares the game for shutting down
280 static void ShutdownGame()
282 IConsoleFree();
284 if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
286 MusicDriver::ShutdownDriver();
287 SoundDriver::ShutdownDriver();
288 VideoDriver::ShutdownDriver();
290 UnInitWindowSystem();
292 /* stop the scripts */
293 AI::Uninitialize(false);
294 Game::Uninitialize(false);
296 /* Uninitialize variables that are allocated dynamically */
297 GamelogReset();
299 #ifdef ENABLE_NETWORK
300 free(_config_file);
301 #endif
303 LinkGraphSchedule::Clear();
304 PoolBase::Clean(PT_ALL);
306 /* No NewGRFs were loaded when it was still bootstrapping. */
307 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
309 /* Close all and any open filehandles */
310 FioCloseAll();
314 * Load the introduction game.
315 * @param load_newgrfs Whether to load the NewGRFs or not.
317 static void LoadIntroGame(bool load_newgrfs = true)
319 _game_mode = GM_MENU;
321 if (load_newgrfs) ResetGRFConfig(false);
323 /* Setup main window */
324 ResetWindowSystem();
325 SetupColoursAndInitialWindow();
327 /* Load the default opening screen savegame */
328 if (!LoadGame ("opntitle.dat", false, false, BASESET_DIR)) {
329 GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
330 WaitTillGeneratedWorld();
331 SetLocalCompany(COMPANY_SPECTATOR);
332 } else {
333 SetLocalCompany(COMPANY_FIRST);
336 _pause_mode = PM_UNPAUSED;
337 _cursor.fix_at = false;
339 CheckForMissingGlyphs();
341 /* Play main theme */
342 if (MusicDriver::GetActiveDriver()->IsSongPlaying()) ResetMusic();
345 void MakeNewgameSettingsLive()
347 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
348 if (_settings_game.ai_config[c] != NULL) {
349 delete _settings_game.ai_config[c];
352 if (_settings_game.game_config != NULL) {
353 delete _settings_game.game_config;
356 /* Copy newgame settings to active settings.
357 * Also initialise old settings needed for savegame conversion. */
358 _settings_game = _settings_newgame;
359 _old_vds = _settings_client.company.vehicle;
360 _old_no_servicing_if_no_breakdowns = true;
362 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
363 _settings_game.ai_config[c] = NULL;
364 if (_settings_newgame.ai_config[c] != NULL) {
365 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
368 _settings_game.game_config = NULL;
369 if (_settings_newgame.game_config != NULL) {
370 _settings_game.game_config = new GameConfig(_settings_newgame.game_config);
374 void OpenBrowser(const char *url)
376 /* Make sure we only accept urls that are sure to open a browser. */
377 if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
379 extern void OSOpenBrowser(const char *url);
380 OSOpenBrowser(url);
383 /** Callback structure of statements to be executed after the NewGRF scan. */
384 struct AfterNewGRFScan : NewGRFScanCallback {
385 Year startyear; ///< The start year.
386 uint generation_seed; ///< Seed for the new game.
387 char *dedicated_host; ///< Hostname for the dedicated server.
388 uint16 dedicated_port; ///< Port for the dedicated server.
389 char *network_conn; ///< Information about the server to connect to, or NULL.
390 const char *join_server_password; ///< The password to join the server with.
391 const char *join_company_password; ///< The password to join the company with.
392 bool *save_config_ptr; ///< The pointer to the save config setting.
393 bool save_config; ///< The save config setting.
396 * Create a new callback.
397 * @param save_config_ptr Pointer to the save_config local variable which
398 * decides whether to save of exit or not.
400 AfterNewGRFScan(bool *save_config_ptr) :
401 startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
402 dedicated_host(NULL), dedicated_port(0), network_conn(NULL),
403 join_server_password(NULL), join_company_password(NULL),
404 save_config_ptr(save_config_ptr), save_config(true)
408 virtual void OnNewGRFsScanned()
410 ResetGRFConfig(false);
412 TarScanner::DoScan(TarScanner::SCENARIO);
414 AI::Initialize();
415 Game::Initialize();
417 /* We want the new (correct) NewGRF count to survive the loading. */
418 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
419 LoadFromConfig();
420 _settings_client.gui.last_newgrf_count = last_newgrf_count;
421 /* Since the default for the palette might have changed due to
422 * reading the configuration file, recalculate that now. */
423 UpdateNewGRFConfigPalette();
425 Game::Uninitialize(true);
426 AI::Uninitialize(true);
427 CheckConfig();
428 LoadFromHighScore();
429 LoadHotkeysFromConfig();
430 WindowDesc::LoadFromConfig();
432 /* We have loaded the config, so we may possibly save it. */
433 *save_config_ptr = save_config;
435 /* restore saved music volume */
436 MusicDriver::GetActiveDriver()->SetVolume(_settings_client.music.music_vol);
438 if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
439 if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
441 #if defined(ENABLE_NETWORK)
442 if (dedicated_host != NULL) {
443 _network_bind_list.Clear();
444 *_network_bind_list.Append() = xstrdup(dedicated_host);
446 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
447 #endif /* ENABLE_NETWORK */
449 /* initialize the ingame console */
450 IConsoleInit();
451 InitializeGUI();
452 IConsoleCmdExec("exec scripts/autoexec.scr 0");
454 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
455 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
457 #ifdef ENABLE_NETWORK
458 if (_network_available && network_conn != NULL) {
459 const char *port = NULL;
460 const char *company = NULL;
461 uint16 rport = NETWORK_DEFAULT_PORT;
462 CompanyID join_as = COMPANY_NEW_COMPANY;
464 ParseConnectionString(&company, &port, network_conn);
466 if (company != NULL) {
467 join_as = (CompanyID)atoi(company);
469 if (join_as != COMPANY_SPECTATOR) {
470 join_as--;
471 if (join_as >= MAX_COMPANIES) {
472 delete this;
473 return;
477 if (port != NULL) rport = atoi(port);
479 LoadIntroGame();
480 _switch_mode = SM_NONE;
481 NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
483 #endif /* ENABLE_NETWORK */
485 /* After the scan we're not used anymore. */
486 delete this;
490 #if defined(UNIX) && !defined(__MORPHOS__)
491 extern void DedicatedFork();
492 #endif
494 /** Options of OpenTTD. */
495 static const OptionData _options[] = {
496 GETOPT_SHORT_VALUE('I'),
497 GETOPT_SHORT_VALUE('S'),
498 GETOPT_SHORT_VALUE('M'),
499 GETOPT_SHORT_VALUE('m'),
500 GETOPT_SHORT_VALUE('s'),
501 GETOPT_SHORT_VALUE('v'),
502 GETOPT_SHORT_VALUE('b'),
503 #if defined(ENABLE_NETWORK)
504 GETOPT_SHORT_OPTVAL('D'),
505 GETOPT_SHORT_OPTVAL('n'),
506 GETOPT_SHORT_VALUE('l'),
507 GETOPT_SHORT_VALUE('p'),
508 GETOPT_SHORT_VALUE('P'),
509 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
510 GETOPT_SHORT_NOVAL('f'),
511 #endif
512 #endif /* ENABLE_NETWORK */
513 GETOPT_SHORT_VALUE('r'),
514 GETOPT_SHORT_VALUE('t'),
515 GETOPT_SHORT_OPTVAL('d'),
516 GETOPT_SHORT_NOVAL('e'),
517 GETOPT_SHORT_OPTVAL('g'),
518 GETOPT_SHORT_VALUE('G'),
519 GETOPT_SHORT_VALUE('c'),
520 GETOPT_SHORT_NOVAL('x'),
521 GETOPT_SHORT_VALUE('q'),
522 GETOPT_SHORT_NOVAL('h'),
523 GETOPT_END()
527 * Main entry point for this lovely game.
528 * @param argc The number of arguments passed to this game.
529 * @param argv The values of the arguments.
530 * @return 0 when there is no error.
532 int openttd_main(int argc, char *argv[])
534 char *musicdriver = NULL;
535 char *sounddriver = NULL;
536 char *videodriver = NULL;
537 char *blitter = NULL;
538 char *graphics_set = NULL;
539 char *sounds_set = NULL;
540 char *music_set = NULL;
541 Dimension resolution = {0, 0};
542 /* AfterNewGRFScan sets save_config to true after scanning completed. */
543 bool save_config = false;
544 AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
545 #if defined(ENABLE_NETWORK)
546 bool dedicated = false;
547 char *debuglog_conn = NULL;
549 extern bool _dedicated_forks;
550 _dedicated_forks = false;
551 #endif /* ENABLE_NETWORK */
553 _game_mode = GM_MENU;
554 _switch_mode = SM_MENU;
555 _config_file = NULL;
557 GetOptData mgo(argc - 1, argv + 1, _options);
558 int ret = 0;
560 int i;
561 while ((i = mgo.GetOpt()) != -1) {
562 switch (i) {
563 case 'I': free(graphics_set); graphics_set = xstrdup(mgo.opt); break;
564 case 'S': free(sounds_set); sounds_set = xstrdup(mgo.opt); break;
565 case 'M': free(music_set); music_set = xstrdup(mgo.opt); break;
566 case 'm': free(musicdriver); musicdriver = xstrdup(mgo.opt); break;
567 case 's': free(sounddriver); sounddriver = xstrdup(mgo.opt); break;
568 case 'v': free(videodriver); videodriver = xstrdup(mgo.opt); break;
569 case 'b': free(blitter); blitter = xstrdup(mgo.opt); break;
570 #if defined(ENABLE_NETWORK)
571 case 'D':
572 free(musicdriver);
573 free(sounddriver);
574 free(videodriver);
575 free(blitter);
576 musicdriver = xstrdup("null");
577 sounddriver = xstrdup("null");
578 videodriver = xstrdup("dedicated");
579 blitter = xstrdup("null");
580 dedicated = true;
581 SetDebugString("net=6");
582 if (mgo.opt != NULL) {
583 /* Use the existing method for parsing (openttd -n).
584 * However, we do ignore the #company part. */
585 const char *temp = NULL;
586 const char *port = NULL;
587 ParseConnectionString(&temp, &port, mgo.opt);
588 if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
589 if (port != NULL) scanner->dedicated_port = atoi(port);
591 break;
592 case 'f': _dedicated_forks = true; break;
593 case 'n':
594 scanner->network_conn = mgo.opt; // optional IP parameter, NULL if unset
595 break;
596 case 'l':
597 debuglog_conn = mgo.opt;
598 break;
599 case 'p':
600 scanner->join_server_password = mgo.opt;
601 break;
602 case 'P':
603 scanner->join_company_password = mgo.opt;
604 break;
605 #endif /* ENABLE_NETWORK */
606 case 'r': ParseResolution(&resolution, mgo.opt); break;
607 case 't': scanner->startyear = atoi(mgo.opt); break;
608 case 'd': {
609 #if defined(WIN32)
610 CreateConsole();
611 #endif
612 if (mgo.opt != NULL) SetDebugString(mgo.opt);
613 break;
615 case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
616 case 'g':
617 if (mgo.opt != NULL) {
618 _file_to_saveload.SetName(mgo.opt);
619 bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
620 _switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
621 _file_to_saveload.SetMode(SLO_LOAD, is_scenario ? FT_SCENARIO : FT_SAVEGAME, DFT_GAME_FILE);
623 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
624 const char *t = strrchr(_file_to_saveload.name, '.');
625 if (t != NULL) {
626 FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, t);
627 if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
630 break;
633 _switch_mode = SM_NEWGAME;
634 /* Give a random map if no seed has been given */
635 if (scanner->generation_seed == GENERATE_NEW_SEED) {
636 scanner->generation_seed = InteractiveRandom();
638 break;
639 case 'q': {
640 DeterminePaths(argv[0]);
641 if (StrEmpty(mgo.opt)) {
642 ret = 1;
643 goto exit_noshutdown;
646 sstring<80> title;
647 FiosGetSavegameListCallback (SLO_LOAD, mgo.opt, strrchr(mgo.opt, '.'), &title);
649 _load_check_data.Clear();
650 bool res = LoadGame (mgo.opt, true, false, SAVE_DIR);
651 if (!res || _load_check_data.HasErrors()) {
652 fprintf(stderr, "Failed to open savegame\n");
653 if (_load_check_data.HasErrors()) {
654 char buf[256];
655 SetDParamStr(0, _load_check_data.error.data);
656 GetString (buf, _load_check_data.error.str);
657 fprintf(stderr, "%s\n", buf);
659 goto exit_noshutdown;
662 WriteSavegameInfo (title.c_str());
664 goto exit_noshutdown;
666 case 'G': scanner->generation_seed = atoi(mgo.opt); break;
667 case 'c': free(_config_file); _config_file = xstrdup(mgo.opt); break;
668 case 'x': scanner->save_config = false; break;
669 case 'h':
670 i = -2; // Force printing of help.
671 break;
673 if (i == -2) break;
676 if (i == -2 || mgo.numleft > 0) {
677 /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
678 * In all cases, print the help, and exit.
680 * The next two functions are needed to list the graphics sets. We can't do them earlier
681 * because then we cannot show it on the debug console as that hasn't been configured yet. */
682 DeterminePaths(argv[0]);
683 TarScanner::DoScan(TarScanner::BASESET);
684 BaseGraphics::FindSets();
685 BaseSounds::FindSets();
686 BaseMusic::FindSets();
687 ShowHelp();
689 goto exit_noshutdown;
692 #if defined(WINCE) && defined(_DEBUG)
693 /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
694 SetDebugString("4");
695 #endif
697 DeterminePaths(argv[0]);
698 TarScanner::DoScan(TarScanner::BASESET);
700 #if defined(ENABLE_NETWORK)
701 if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
702 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
704 #if defined(UNIX) && !defined(__MORPHOS__)
705 /* We must fork here, or we'll end up without some resources we need (like sockets) */
706 if (_dedicated_forks) DedicatedFork();
707 #endif
708 #endif
710 LoadFromConfig(true);
712 if (resolution.width != 0) _cur_resolution = resolution;
715 * The width and height must be at least 1 pixel and width times
716 * height times bytes per pixel must still fit within a 32 bits
717 * integer, even for 32 bpp video modes. This way all internal
718 * drawing routines work correctly.
720 _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX / 2);
721 _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
723 /* Assume the cursor starts within the game as not all video drivers
724 * get an event that the cursor is within the window when it is opened.
725 * Saying the cursor is there makes no visible difference as it would
726 * just be out of the bounds of the window. */
727 _cursor.in_window = true;
729 /* enumerate language files */
730 InitializeLanguagePacks();
732 /* Initialize the regular font for FreeType */
733 InitFreeType(false);
735 /* This must be done early, since functions use the SetWindowDirty* calls */
736 InitWindowSystem();
738 BaseGraphics::FindSets();
740 const char *sel = (graphics_set != NULL) ? graphics_set : BaseGraphics::ini_set;
741 if (!BaseGraphics::SetSet (sel) && !StrEmpty (sel)) {
742 BaseGraphics::SetSet(NULL);
744 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
745 msg.SetDParamStr (0, sel);
746 ScheduleErrorMessage(msg);
749 free(graphics_set);
751 /* Initialize game palette */
752 GfxInitPalettes();
754 DEBUG(misc, 1, "Loading blitter...");
756 const char *sel = (blitter != NULL) ? blitter : Blitter::ini;
757 bool autodetect = StrEmpty (sel);
758 Blitter::autodetected = autodetect;
759 /* Activate the initial blitter.
760 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
761 * - Never guess anything, if the user specified a blitter. (Blitter::autodetected)
762 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
763 * - Use 8bpp blitter otherwise.
765 if (autodetect) {
766 #ifdef DEDICATED
767 sel = "null";
768 #else
769 bool use_32bpp = (_support8bpp == S8BPP_NONE)
770 || (BaseGraphics::GetUsedSet() != NULL && BaseGraphics::GetUsedSet()->blitter != BLT_8BPP);
771 #ifdef WITH_COCOA
772 /* Some people reported lack of fullscreen support in
773 * 8 bpp mode. While we prefer 8 bpp since it's
774 * faster, we will still have to test for support. */
775 bool QZ_CanDisplay8bpp();
776 if (!use_32bpp && !QZ_CanDisplay8bpp()) {
777 /* The main display can't go to 8 bpp fullscreen mode.
778 * We will have to switch to 32 bpp by default. */
779 use_32bpp = true;
781 #endif /* WITH_COCOA */
782 sel = use_32bpp ? "32bpp-anim" : "8bpp-optimized";
783 #endif /* DEDICATED */
784 DEBUG(driver, 1, "Probing blitter %s", sel);
787 const Blitter::Info *blitter = Blitter::find (sel);
788 if (blitter == NULL) {
789 assert (!autodetect);
790 usererror ("Failed to select requested blitter '%s'; does it exist?", sel);
792 Blitter::select (blitter);
794 free(blitter);
796 VideoDriver::SelectDriver ((videodriver != NULL) ? videodriver : VideoDriver::ini);
797 free(videodriver);
799 NetworkStartUp(); // initialize network-core
801 #if defined(ENABLE_NETWORK)
802 if (debuglog_conn != NULL && _network_available) {
803 const char *not_used = NULL;
804 const char *port = NULL;
805 uint16 rport;
807 rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
809 ParseConnectionString(&not_used, &port, debuglog_conn);
810 if (port != NULL) rport = atoi(port);
812 NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
814 #endif /* ENABLE_NETWORK */
816 if (!HandleBootstrap()) {
817 ShutdownGame();
819 goto exit_bootstrap;
822 VideoDriver::GetActiveDriver()->ClaimMousePointer();
824 /* initialize screenshot formats */
825 InitializeScreenshotFormats();
827 BaseSounds::FindSets();
829 const char *sel = (sounds_set != NULL) ? sounds_set : BaseSounds::ini_set;
830 if (!BaseSounds::SetSet (sel)) {
831 if (StrEmpty (sel) || !BaseSounds::SetSet (NULL)) {
832 usererror ("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
833 } else {
834 ErrorMessageData msg (STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
835 msg.SetDParamStr (0, sel);
836 ScheduleErrorMessage (msg);
840 free(sounds_set);
842 BaseMusic::FindSets();
844 const char *sel = (music_set != NULL) ? music_set : BaseMusic::ini_set;
845 if (!BaseMusic::SetSet (sel)) {
846 if (StrEmpty (sel) || !BaseMusic::SetSet (NULL)) {
847 usererror ("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
848 } else {
849 ErrorMessageData msg (STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
850 msg.SetDParamStr (0, sel);
851 ScheduleErrorMessage (msg);
855 free(music_set);
857 SoundDriver::SelectDriver ((sounddriver != NULL) ? sounddriver : SoundDriver::ini);
858 free(sounddriver);
860 MusicDriver::SelectDriver ((musicdriver != NULL) ? musicdriver : MusicDriver::ini);
861 free(musicdriver);
863 /* Take our initial lock on whatever we might want to do! */
864 _modal_progress_paint_mutex->BeginCritical();
865 _modal_progress_work_mutex->BeginCritical();
867 GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
868 WaitTillGeneratedWorld();
870 LoadIntroGame(false);
872 CheckForMissingGlyphs();
874 /* ScanNewGRFFiles now has control over the scanner. */
875 ScanNewGRFFiles(scanner);
876 scanner = NULL;
878 if (IsExperimentalSavegameVersion()) {
879 ErrorMessageData msg(STR_WARNING_EXPERIMENTAL_SAVEGAME_VERSION_1, STR_WARNING_EXPERIMENTAL_SAVEGAME_VERSION_2);
880 ScheduleErrorMessage(msg);
883 VideoDriver::GetActiveDriver()->MainLoop();
885 WaitTillSaved();
887 /* only save config if we have to */
888 if (save_config) {
889 SaveToConfig();
890 SaveHotkeysToConfig();
891 WindowDesc::SaveToConfig();
892 SaveToHighScore();
895 /* Reset windowing system, stop drivers, free used memory, ... */
896 ShutdownGame();
897 goto exit_normal;
899 exit_noshutdown:
900 /* These three are normally freed before bootstrap. */
901 free(graphics_set);
902 free(videodriver);
903 free(blitter);
905 exit_bootstrap:
906 /* These are normally freed before exit, but after bootstrap. */
907 free(sounds_set);
908 free(music_set);
909 free(musicdriver);
910 free(sounddriver);
912 exit_normal:
913 free(BaseGraphics::ini_set);
914 free(BaseSounds::ini_set);
915 free(BaseMusic::ini_set);
917 free (MusicDriver::ini);
918 free (SoundDriver::ini);
919 free (VideoDriver::ini);
920 free (Blitter::ini);
922 delete scanner;
924 #ifdef ENABLE_NETWORK
925 extern FILE *_log_fd;
926 if (_log_fd != NULL) {
927 fclose(_log_fd);
929 #endif /* ENABLE_NETWORK */
931 return ret;
934 void HandleExitGameRequest()
936 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
937 _exit_game = true;
938 } else if (_settings_client.gui.autosave_on_exit) {
939 DoExitSave();
940 _exit_game = true;
941 } else {
942 AskExitGame();
946 static void MakeNewGameDone()
948 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
950 /* In a dedicated server, the server does not play */
951 if (!VideoDriver::GetActiveDriver()->HasGUI()) {
952 SetLocalCompany(COMPANY_SPECTATOR);
953 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
954 IConsoleCmdExec("exec scripts/game_start.scr 0");
955 return;
958 /* Create a single company */
959 DoStartupNewCompany(false);
961 Company *c = Company::Get(COMPANY_FIRST);
962 c->settings = _settings_client.company;
964 IConsoleCmdExec("exec scripts/game_start.scr 0");
966 SetLocalCompany(COMPANY_FIRST);
968 InitializeRailGUI();
970 #ifdef ENABLE_NETWORK
971 /* We are the server, we start a new company (not dedicated),
972 * so set the default password *if* needed. */
973 if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
974 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
976 #endif /* ENABLE_NETWORK */
978 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
980 CheckEngines();
981 CheckIndustries();
982 MarkWholeScreenDirty();
985 static void MakeNewGame(bool from_heightmap, bool reset_settings)
987 _game_mode = GM_NORMAL;
989 ResetGRFConfig(true);
991 GenerateWorldSetCallback(&MakeNewGameDone);
992 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
995 static void MakeNewEditorWorldDone()
997 SetLocalCompany(OWNER_NONE);
1000 static void MakeNewEditorWorld()
1002 _game_mode = GM_EDITOR;
1004 ResetGRFConfig(true);
1006 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
1007 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1011 * Load the specified savegame but on error do different things.
1012 * If loading fails due to corrupt savegame, bad version, etc. go back to
1013 * a previous correct state. In the menu for example load the intro game again.
1014 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
1015 * @param newgm switch to this mode of loading fails due to some unknown error
1016 * @param filename file to be loaded
1017 * @param subdir default directory to look for filename, set to 0 if not needed
1018 * @param lf Load filter to use, if NULL: use filename + subdir.
1020 bool SafeLoad (const char *filename, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
1022 assert(dft == DFT_GAME_FILE || (lf == NULL && dft == DFT_OLD_GAME_FILE));
1023 GameMode ogm = _game_mode;
1025 _game_mode = newgm;
1027 if (lf == NULL ? LoadGame (filename, false, dft == DFT_OLD_GAME_FILE, subdir) : LoadWithFilter (lf)) {
1028 return true;
1029 } else {
1030 #ifdef ENABLE_NETWORK
1031 if (_network_dedicated) {
1033 * We need to reinit a network map...
1034 * We can't simply load the intro game here as that game has many
1035 * special cases which make clients desync immediately. So we fall
1036 * back to just generating a new game with the current settings.
1038 DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
1039 MakeNewGame(false, true);
1040 return false;
1042 if (_network_server) {
1043 /* We can't load the intro game as server, so disconnect first. */
1044 NetworkDisconnect();
1046 #endif /* ENABLE_NETWORK */
1048 switch (ogm) {
1049 default:
1050 case GM_MENU: LoadIntroGame(); break;
1051 case GM_EDITOR: MakeNewEditorWorld(); break;
1053 return false;
1057 void SwitchToMode(SwitchMode new_mode)
1059 #ifdef ENABLE_NETWORK
1060 /* If we are saving something, the network stays in his current state */
1061 if (new_mode != SM_SAVE_GAME) {
1062 /* If the network is active, make it not-active */
1063 if (_networking) {
1064 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1065 NetworkReboot();
1066 } else {
1067 NetworkDisconnect();
1071 /* If we are a server, we restart the server */
1072 if (_is_network_server) {
1073 /* But not if we are going to the menu */
1074 if (new_mode != SM_MENU) {
1075 /* check if we should reload the config */
1076 if (_settings_client.network.reload_cfg) {
1077 LoadFromConfig();
1078 MakeNewgameSettingsLive();
1079 ResetGRFConfig(false);
1081 NetworkServerStart();
1082 } else {
1083 /* This client no longer wants to be a network-server */
1084 _is_network_server = false;
1088 #endif /* ENABLE_NETWORK */
1089 /* Make sure all AI controllers are gone at quitting game */
1090 if (new_mode != SM_SAVE_GAME) AI::KillAll();
1092 switch (new_mode) {
1093 case SM_EDITOR: // Switch to scenario editor
1094 MakeNewEditorWorld();
1095 break;
1097 case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1098 case SM_NEWGAME: // New Game --> 'Random game'
1099 #ifdef ENABLE_NETWORK
1100 if (_network_server) {
1101 bstrcpy (_network_game_info.map_name, "Random Map");
1103 #endif /* ENABLE_NETWORK */
1104 MakeNewGame(false, new_mode == SM_NEWGAME);
1105 break;
1107 case SM_LOAD_GAME: { // Load game, Play Scenario
1108 ResetGRFConfig(true);
1109 ResetWindowSystem();
1111 assert (_file_to_saveload.file_op == SLO_LOAD);
1112 if (!SafeLoad (_file_to_saveload.name, _file_to_saveload.detail_ftype, GM_NORMAL, NO_DIRECTORY)) {
1113 ShowSaveLoadErrorMessage (false);
1114 } else {
1115 if (_file_to_saveload.abstract_ftype == FT_SCENARIO) {
1116 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1117 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1119 /* Update the local company for a loaded game. It is either always
1120 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1121 SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
1122 /* Execute the game-start script */
1123 IConsoleCmdExec("exec scripts/game_start.scr 0");
1124 /* Decrease pause counter (was increased from opening load dialog) */
1125 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1126 #ifdef ENABLE_NETWORK
1127 if (_network_server) {
1128 bstrfmt (_network_game_info.map_name, "%s (Loaded game)", _file_to_saveload.title);
1130 #endif /* ENABLE_NETWORK */
1132 break;
1135 case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1136 #ifdef ENABLE_NETWORK
1137 if (_network_server) {
1138 bstrfmt (_network_game_info.map_name, "%s (Heightmap)", _file_to_saveload.title);
1140 #endif /* ENABLE_NETWORK */
1141 MakeNewGame(true, true);
1142 break;
1144 case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1145 SetLocalCompany(OWNER_NONE);
1147 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1148 MarkWholeScreenDirty();
1149 break;
1151 case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1152 assert (_file_to_saveload.file_op == SLO_LOAD);
1153 if (SafeLoad (_file_to_saveload.name, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) {
1154 SetLocalCompany(OWNER_NONE);
1155 _settings_newgame.game_creation.starting_year = _cur_year;
1156 /* Cancel the saveload pausing */
1157 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1158 } else {
1159 ShowSaveLoadErrorMessage (false);
1161 break;
1164 case SM_MENU: // Switch to game intro menu
1165 LoadIntroGame();
1166 if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
1167 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1168 BaseSounds::ini_set = xstrdup(BaseSounds::GetUsedSet()->get_name());
1170 break;
1172 case SM_SAVE_GAME: // Save game.
1173 /* Make network saved games on pause compatible to singleplayer */
1174 if (!SaveGame(_file_to_saveload.name, NO_DIRECTORY)) {
1175 ShowSaveLoadErrorMessage (true);
1176 } else {
1177 DeleteWindowById(WC_SAVELOAD, 0);
1179 break;
1181 case SM_SAVE_HEIGHTMAP: // Save heightmap.
1182 MakeHeightmapScreenshot(_file_to_saveload.name);
1183 DeleteWindowById(WC_SAVELOAD, 0);
1184 break;
1186 case SM_GENRANDLAND: // Generate random land within scenario editor
1187 SetLocalCompany(OWNER_NONE);
1188 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1189 /* XXX: set date */
1190 MarkWholeScreenDirty();
1191 break;
1193 default: NOT_REACHED();
1199 * Check the validity of some of the caches.
1200 * Especially in the sense of desyncs between
1201 * the cached value and what the value would
1202 * be when calculated from the 'base' data.
1204 static void CheckCaches()
1206 /* Return here so it is easy to add checks that are run
1207 * always to aid testing of caches. */
1208 if (_debug_desync_level <= 1) return;
1210 /* Check the town caches. */
1211 SmallVector<TownCache, 4> old_town_caches;
1212 Town *t;
1213 FOR_ALL_TOWNS(t) {
1214 MemCpyT(old_town_caches.Append(), &t->cache);
1217 extern void RebuildTownCaches();
1218 RebuildTownCaches();
1219 RebuildSubsidisedSourceAndDestinationCache();
1221 uint i = 0;
1222 FOR_ALL_TOWNS(t) {
1223 if (MemCmpT(old_town_caches.Get(i), &t->cache) != 0) {
1224 DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
1226 i++;
1229 /* Check company infrastructure cache. */
1230 SmallVector<CompanyInfrastructure, 4> old_infrastructure;
1231 Company *c;
1232 FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
1234 extern void AfterLoadCompanyStats();
1235 AfterLoadCompanyStats();
1237 i = 0;
1238 FOR_ALL_COMPANIES(c) {
1239 if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
1240 DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
1242 i++;
1245 /* Strict checking of the road stop cache entries */
1246 const RoadStop *rs;
1247 FOR_ALL_ROADSTOPS(rs) {
1248 if (!IsStandardRoadStopTile(rs->xy)) rs->CheckIntegrity();
1251 Vehicle *v;
1252 FOR_ALL_VEHICLES(v) {
1253 extern void FillNewGRFVehicleCache(const Vehicle *v);
1254 if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1256 uint length = 0;
1257 for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
1259 NewGRFCache *grf_cache = xcalloct<NewGRFCache>(length);
1260 VehicleCache *veh_cache = xcalloct<VehicleCache>(length);
1261 GroundVehicleCache *gro_cache = xcalloct<GroundVehicleCache>(length);
1262 TrainCache *tra_cache = xcalloct<TrainCache>(length);
1264 length = 0;
1265 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1266 FillNewGRFVehicleCache(u);
1267 grf_cache[length] = u->grf_cache;
1268 veh_cache[length] = u->vcache;
1269 switch (u->type) {
1270 case VEH_TRAIN:
1271 gro_cache[length] = Train::From(u)->gcache;
1272 tra_cache[length] = Train::From(u)->tcache;
1273 break;
1274 case VEH_ROAD:
1275 gro_cache[length] = RoadVehicle::From(u)->gcache;
1276 break;
1277 default:
1278 break;
1280 length++;
1283 switch (v->type) {
1284 case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
1285 case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
1286 case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
1287 case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
1288 default: break;
1291 length = 0;
1292 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1293 FillNewGRFVehicleCache(u);
1294 if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1295 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);
1297 if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1298 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);
1300 switch (u->type) {
1301 case VEH_TRAIN:
1302 if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1303 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);
1305 if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1306 DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1308 break;
1309 case VEH_ROAD:
1310 if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1311 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);
1313 break;
1314 default:
1315 break;
1317 length++;
1320 free(grf_cache);
1321 free(veh_cache);
1322 free(gro_cache);
1323 free(tra_cache);
1326 /* Check whether the caches are still valid */
1327 FOR_ALL_VEHICLES(v) {
1328 byte buff[sizeof(VehicleCargoList)];
1329 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1330 v->cargo.InvalidateCache();
1331 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1334 Station *st;
1335 FOR_ALL_STATIONS(st) {
1336 for (CargoID c = 0; c < NUM_CARGO; c++) {
1337 byte buff[sizeof(StationCargoList)];
1338 memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
1339 st->goods[c].cargo.InvalidateCache();
1340 assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
1346 * State controlling game loop.
1347 * The state must not be changed from anywhere but here.
1348 * That check is enforced in DoCommand.
1350 void StateGameLoop()
1352 /* don't execute the state loop during pause */
1353 if (_pause_mode != PM_UNPAUSED) {
1354 UpdateLandscapingLimits();
1355 #ifndef DEBUG_DUMP_COMMANDS
1356 Game::GameLoop();
1357 #endif
1358 CallWindowTickEvent();
1359 return;
1361 if (HasModalProgress()) return;
1363 Layouter::ReduceLineCache();
1365 if (_game_mode == GM_EDITOR) {
1366 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1367 RunTileLoop();
1368 CallVehicleTicks();
1369 CallLandscapeTick();
1370 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1371 UpdateLandscapingLimits();
1373 CallWindowTickEvent();
1374 NewsLoop();
1375 } else {
1376 if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
1377 /* Save the desync savegame if needed. */
1378 char name[MAX_PATH];
1379 bstrfmt (name, "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
1380 SaveGame(name, AUTOSAVE_DIR, false);
1383 CheckCaches();
1385 /* All these actions has to be done from OWNER_NONE
1386 * for multiplayer compatibility */
1387 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1389 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1390 AnimateAnimatedTiles();
1391 IncreaseDate();
1392 RunTileLoop();
1393 CallVehicleTicks();
1394 CallLandscapeTick();
1395 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1397 #ifndef DEBUG_DUMP_COMMANDS
1398 AI::GameLoop();
1399 Game::GameLoop();
1400 #endif
1401 UpdateLandscapingLimits();
1403 CallWindowTickEvent();
1404 NewsLoop();
1405 cur_company.Restore();
1408 assert(IsLocalCompany());
1412 * Create an autosave. The default name is "autosave#.sav". However with
1413 * the setting 'keep_all_autosave' the name defaults to company-name + date
1415 static void DoAutosave()
1417 sstring<MAX_PATH> buf;
1419 #if defined(PSP)
1420 /* Autosaving in networking is too time expensive for the PSP */
1421 if (_networking) return;
1422 #endif /* PSP */
1424 if (_settings_client.gui.keep_all_autosave) {
1425 GenerateDefaultSaveName (&buf);
1426 buf.append (".sav");
1427 } else {
1428 static int _autosave_ctr = 0;
1430 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1431 buf.fmt ("autosave%d.sav", _autosave_ctr);
1433 if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
1436 DEBUG(sl, 2, "Autosaving to '%s'", buf.c_str());
1437 if (!SaveGame(buf.c_str(), AUTOSAVE_DIR)) {
1438 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
1442 void GameLoop()
1444 if (_game_mode == GM_BOOTSTRAP) {
1445 #ifdef ENABLE_NETWORK
1446 /* Check for UDP stuff */
1447 if (_network_available) NetworkBackgroundLoop();
1448 #endif
1449 InputLoop();
1450 return;
1453 ProcessAsyncSaveFinish();
1455 /* autosave game? */
1456 if (_do_autosave) {
1457 DoAutosave();
1458 _do_autosave = false;
1459 SetWindowDirty(WC_STATUS_BAR, 0);
1462 /* switch game mode? */
1463 if (_switch_mode != SM_NONE && !HasModalProgress()) {
1464 SwitchToMode(_switch_mode);
1465 _switch_mode = SM_NONE;
1468 IncreaseSpriteLRU();
1469 InteractiveRandom();
1471 extern int _caret_timer;
1472 _caret_timer += 3;
1473 CursorTick();
1475 #ifdef ENABLE_NETWORK
1476 /* Check for UDP stuff */
1477 if (_network_available) NetworkBackgroundLoop();
1479 if (_networking && !HasModalProgress()) {
1480 /* Multiplayer */
1481 NetworkGameLoop();
1482 } else {
1483 if (_network_reconnect > 0 && --_network_reconnect == 0) {
1484 /* This means that we want to reconnect to the last host
1485 * We do this here, because it means that the network is really closed */
1486 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
1488 /* Singleplayer */
1489 StateGameLoop();
1492 /* Check chat messages roughly once a second. */
1493 static uint check_message = 0;
1494 if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
1495 check_message = 0;
1496 NetworkChatMessageLoop();
1498 #else
1499 StateGameLoop();
1500 #endif /* ENABLE_NETWORK */
1502 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1504 if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
1506 InputLoop();
1508 SoundDriver::GetActiveDriver()->MainLoop();
1509 MusicLoop();