Invalidate the right goal list when changing goals
[openttd/fttd.git] / src / openttd.cpp
blobf6a51ea208a1792edbe8d135646a227b4db1e1d4
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/factory.hpp"
15 #include "sound/sound_driver.hpp"
16 #include "music/music_driver.hpp"
17 #include "video/video_driver.hpp"
19 #include "fontcache.h"
20 #include "error.h"
21 #include "gui.h"
23 #include "base_media_base.h"
24 #include "saveload/saveload.h"
25 #include "company_func.h"
26 #include "command_func.h"
27 #include "news_func.h"
28 #include "fios.h"
29 #include "aircraft.h"
30 #include "roadveh.h"
31 #include "train.h"
32 #include "ship.h"
33 #include "console_func.h"
34 #include "screenshot.h"
35 #include "network/network.h"
36 #include "network/network_func.h"
37 #include "ai/ai.hpp"
38 #include "ai/ai_config.hpp"
39 #include "settings_func.h"
40 #include "genworld.h"
41 #include "progress.h"
42 #include "strings_func.h"
43 #include "date_func.h"
44 #include "vehicle_func.h"
45 #include "gamelog.h"
46 #include "animated_tile_func.h"
47 #include "roadstop_base.h"
48 #include "elrail_func.h"
49 #include "rev.h"
50 #include "highscore.h"
51 #include "station_base.h"
52 #include "crashlog.h"
53 #include "engine_func.h"
54 #include "core/random_func.hpp"
55 #include "rail_gui.h"
56 #include "core/backup_type.hpp"
57 #include "hotkeys.h"
58 #include "newgrf.h"
59 #include "misc/getoptdata.h"
60 #include "game/game.hpp"
61 #include "game/game_config.hpp"
62 #include "town.h"
63 #include "subsidy_func.h"
64 #include "gfx_layout.h"
65 #include "viewport_sprite_sorter.h"
67 #include "linkgraph/linkgraphschedule.h"
69 #include <stdarg.h>
71 void CallLandscapeTick();
72 void IncreaseDate();
73 void DoPaletteAnimations();
74 void MusicLoop();
75 void ResetMusic();
76 void CallWindowTickEvent();
77 bool HandleBootstrap();
79 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
80 extern void ShowOSErrorBox(const char *buf, bool system);
81 extern char *_config_file;
83 /**
84 * Error handling for fatal user errors.
85 * @param s the string to print.
86 * @note Does NEVER return.
88 void CDECL usererror(const char *s, ...)
90 va_list va;
91 char buf[512];
93 va_start(va, s);
94 vsnprintf(buf, lengthof(buf), s, va);
95 va_end(va);
97 ShowOSErrorBox(buf, false);
98 if (_video_driver != NULL) _video_driver->Stop();
100 exit(1);
104 * Error handling for fatal non-user errors.
105 * @param s the string to print.
106 * @note Does NEVER return.
108 void CDECL error(const char *s, ...)
110 va_list va;
111 char buf[512];
113 va_start(va, s);
114 vsnprintf(buf, lengthof(buf), s, va);
115 va_end(va);
117 ShowOSErrorBox(buf, true);
119 /* Set the error message for the crash log and then invoke it. */
120 CrashLog::SetErrorMessage(buf);
121 abort();
125 * Shows some information on the console/a popup box depending on the OS.
126 * @param str the text to show.
128 void CDECL ShowInfoF(const char *str, ...)
130 va_list va;
131 char buf[1024];
132 va_start(va, str);
133 vsnprintf(buf, lengthof(buf), str, va);
134 va_end(va);
135 ShowInfo(buf);
139 * Show the help message when someone passed a wrong parameter.
141 static void ShowHelp()
143 char buf[8192];
144 char *p = buf;
146 p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
147 p = strecpy(p,
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",
179 lastof(buf)
182 /* List the graphics packs */
183 p = BaseGraphics::GetSetsList(p, lastof(buf));
185 /* List the sounds packs */
186 p = BaseSounds::GetSetsList(p, lastof(buf));
188 /* List the music packs */
189 p = BaseMusic::GetSetsList(p, lastof(buf));
191 /* List the drivers */
192 p = DriverFactoryBase::GetDriversInfo(p, lastof(buf));
194 /* List the blitters */
195 p = BlitterFactory::GetBlittersInfo(p, lastof(buf));
197 /* List the debug facilities. */
198 p = DumpDebugFacilityNames(p, lastof(buf));
200 /* We need to initialize the AI, so it finds the AIs */
201 AI::Initialize();
202 p = AI::GetConsoleList(p, lastof(buf), true);
203 AI::Uninitialize(true);
205 /* We need to initialize the GameScript, so it finds the GSs */
206 Game::Initialize();
207 p = Game::GetConsoleList(p, lastof(buf), true);
208 Game::Uninitialize(true);
210 /* ShowInfo put output to stderr, but version information should go
211 * to stdout; this is the only exception */
212 #if !defined(WIN32) && !defined(WIN64)
213 printf("%s\n", buf);
214 #else
215 ShowInfo(buf);
216 #endif
219 static void WriteSavegameInfo(const char *name)
221 uint32 last_ottd_rev = 0;
222 byte ever_modified = 0;
223 bool removed_newgrfs = false;
225 GamelogInfo(&_load_check_data.gamelog, &last_ottd_rev, &ever_modified, &removed_newgrfs);
227 char buf[8192];
228 char *p = buf;
229 p += seprintf(p, lastof(buf), "Name: %s\n", name);
230 p += seprintf(p, lastof(buf), "Savegame ver: %c%d\n", _load_check_data.sl_version.type == SGT_FTTD ? 'F' : 'O', _load_check_data.sl_version.fttd.version);
231 p += seprintf(p, lastof(buf), "NewGRF ver: 0x%08X\n", last_ottd_rev);
232 p += seprintf(p, lastof(buf), "Modified: %d\n", ever_modified);
234 if (removed_newgrfs) {
235 p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
238 p = strecpy(p, "NewGRFs:\n", lastof(buf));
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, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
243 p += seprintf(p, lastof(buf), "%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);
251 #else
252 ShowInfo(buf);
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 DriverFactoryBase::ShutdownDrivers();
288 UnInitWindowSystem();
290 /* stop the scripts */
291 AI::Uninitialize(false);
292 Game::Uninitialize(false);
294 /* Uninitialize variables that are allocated dynamically */
295 GamelogReset();
297 #ifdef ENABLE_NETWORK
298 free(_config_file);
299 #endif
301 LinkGraphSchedule::Clear();
302 PoolBase::Clean(PT_ALL);
304 /* No NewGRFs were loaded when it was still bootstrapping. */
305 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
307 /* Close all and any open filehandles */
308 FioCloseAll();
310 UninitFreeType();
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", SL_LOAD, 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 if (load_newgrfs) CheckForMissingSprites();
340 CheckForMissingGlyphs();
342 /* Play main theme */
343 if (_music_driver->IsSongPlaying()) ResetMusic();
346 void MakeNewgameSettingsLive()
348 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
349 if (_settings_game.ai_config[c] != NULL) {
350 delete _settings_game.ai_config[c];
353 if (_settings_game.game_config != NULL) {
354 delete _settings_game.game_config;
357 /* Copy newgame settings to active settings.
358 * Also initialise old settings needed for savegame conversion. */
359 _settings_game = _settings_newgame;
360 _old_vds = _settings_client.company.vehicle;
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 _music_driver->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() = strdup(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 = strdup(mgo.opt); break;
564 case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
565 case 'M': free(music_set); music_set = strdup(mgo.opt); break;
566 case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
567 case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
568 case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
569 case 'b': free(blitter); blitter = strdup(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 = strdup("null");
577 sounddriver = strdup("null");
578 videodriver = strdup("dedicated");
579 blitter = strdup("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 strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
619 _switch_mode = (_switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_LOAD_GAME);
620 _file_to_saveload.mode = SL_LOAD;
622 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
623 const char *t = strrchr(_file_to_saveload.name, '.');
624 if (t != NULL) {
625 FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
626 if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
629 break;
632 _switch_mode = SM_NEWGAME;
633 /* Give a random map if no seed has been given */
634 if (scanner->generation_seed == GENERATE_NEW_SEED) {
635 scanner->generation_seed = InteractiveRandom();
637 break;
638 case 'q': {
639 DeterminePaths(argv[0]);
640 if (StrEmpty(mgo.opt)) {
641 ret = 1;
642 goto exit_noshutdown;
645 char title[80];
646 title[0] = '\0';
647 FiosGetSavegameListCallback(SLD_LOAD_GAME, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
649 _load_check_data.Clear();
650 bool res = LoadGame(mgo.opt, SL_LOAD_CHECK, 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, lastof(buf));
657 fprintf(stderr, "%s\n", buf);
659 goto exit_noshutdown;
662 WriteSavegameInfo(title);
664 goto exit_noshutdown;
666 case 'G': scanner->generation_seed = atoi(mgo.opt); break;
667 case 'c': _config_file = strdup(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();
739 if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = strdup(BaseGraphics::ini_set);
740 if (!BaseGraphics::SetSet(graphics_set)) {
741 if (!StrEmpty(graphics_set)) {
742 BaseGraphics::SetSet(NULL);
744 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
745 msg.SetDParamStr(0, graphics_set);
746 ScheduleErrorMessage(msg);
749 free(graphics_set);
751 /* Initialize game palette */
752 GfxInitPalettes();
754 DEBUG(misc, 1, "Loading blitter...");
755 if (blitter == NULL && _ini_blitter != NULL) blitter = strdup(_ini_blitter);
756 _blitter_autodetected = StrEmpty(blitter);
757 /* If we have a 32 bpp base set, try to select the 32 bpp blitter first, but only if we autoprobe the blitter. */
758 if (!_blitter_autodetected || BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP || BlitterFactory::SelectBlitter("32bpp-anim") == NULL) {
759 if (BlitterFactory::SelectBlitter(blitter) == NULL) {
760 StrEmpty(blitter) ?
761 usererror("Failed to autoprobe blitter") :
762 usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
765 free(blitter);
767 if (videodriver == NULL && _ini_videodriver != NULL) videodriver = strdup(_ini_videodriver);
768 _video_driver = (VideoDriver*)DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
769 if (_video_driver == NULL) {
770 StrEmpty(videodriver) ?
771 usererror("Failed to autoprobe video driver") :
772 usererror("Failed to select requested video driver '%s'", videodriver);
774 free(videodriver);
776 InitializeSpriteSorter();
778 /* Initialize the zoom level of the screen to normal */
779 _screen.zoom = ZOOM_LVL_NORMAL;
781 NetworkStartUp(); // initialize network-core
783 #if defined(ENABLE_NETWORK)
784 if (debuglog_conn != NULL && _network_available) {
785 const char *not_used = NULL;
786 const char *port = NULL;
787 uint16 rport;
789 rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
791 ParseConnectionString(&not_used, &port, debuglog_conn);
792 if (port != NULL) rport = atoi(port);
794 NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
796 #endif /* ENABLE_NETWORK */
798 if (!HandleBootstrap()) {
799 ShutdownGame();
801 goto exit_bootstrap;
804 _video_driver->ClaimMousePointer();
806 /* initialize screenshot formats */
807 InitializeScreenshotFormats();
809 BaseSounds::FindSets();
810 if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = strdup(BaseSounds::ini_set);
811 if (!BaseSounds::SetSet(sounds_set)) {
812 if (StrEmpty(sounds_set) || !BaseSounds::SetSet(NULL)) {
813 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
814 } else {
815 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
816 msg.SetDParamStr(0, sounds_set);
817 ScheduleErrorMessage(msg);
820 free(sounds_set);
822 BaseMusic::FindSets();
823 if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = strdup(BaseMusic::ini_set);
824 if (!BaseMusic::SetSet(music_set)) {
825 if (StrEmpty(music_set) || !BaseMusic::SetSet(NULL)) {
826 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
827 } else {
828 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
829 msg.SetDParamStr(0, music_set);
830 ScheduleErrorMessage(msg);
833 free(music_set);
835 if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = strdup(_ini_sounddriver);
836 _sound_driver = (SoundDriver*)DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
837 if (_sound_driver == NULL) {
838 StrEmpty(sounddriver) ?
839 usererror("Failed to autoprobe sound driver") :
840 usererror("Failed to select requested sound driver '%s'", sounddriver);
842 free(sounddriver);
844 if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = strdup(_ini_musicdriver);
845 _music_driver = (MusicDriver*)DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
846 if (_music_driver == NULL) {
847 StrEmpty(musicdriver) ?
848 usererror("Failed to autoprobe music driver") :
849 usererror("Failed to select requested music driver '%s'", musicdriver);
851 free(musicdriver);
853 /* Take our initial lock on whatever we might want to do! */
854 _modal_progress_paint_mutex->BeginCritical();
855 _modal_progress_work_mutex->BeginCritical();
857 GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
858 WaitTillGeneratedWorld();
860 LoadIntroGame(false);
862 CheckForMissingGlyphs();
864 /* ScanNewGRFFiles now has control over the scanner. */
865 ScanNewGRFFiles(scanner);
866 scanner = NULL;
868 if (IsExperimentalSavegameVersion()) {
869 ErrorMessageData msg(STR_WARNING_EXPERIMENTAL_SAVEGAME_VERSION_1, STR_WARNING_EXPERIMENTAL_SAVEGAME_VERSION_2);
870 ScheduleErrorMessage(msg);
873 _video_driver->MainLoop();
875 WaitTillSaved();
877 /* only save config if we have to */
878 if (save_config) {
879 SaveToConfig();
880 SaveHotkeysToConfig();
881 WindowDesc::SaveToConfig();
882 SaveToHighScore();
885 /* Reset windowing system, stop drivers, free used memory, ... */
886 ShutdownGame();
887 goto exit_normal;
889 exit_noshutdown:
890 /* These three are normally freed before bootstrap. */
891 free(graphics_set);
892 free(videodriver);
893 free(blitter);
895 exit_bootstrap:
896 /* These are normally freed before exit, but after bootstrap. */
897 free(sounds_set);
898 free(music_set);
899 free(musicdriver);
900 free(sounddriver);
902 exit_normal:
903 free(BaseGraphics::ini_set);
904 free(BaseSounds::ini_set);
905 free(BaseMusic::ini_set);
907 free(_ini_musicdriver);
908 free(_ini_sounddriver);
909 free(_ini_videodriver);
910 free(_ini_blitter);
912 delete scanner;
914 #ifdef ENABLE_NETWORK
915 extern FILE *_log_fd;
916 if (_log_fd != NULL) {
917 fclose(_log_fd);
919 #endif /* ENABLE_NETWORK */
921 return ret;
924 void HandleExitGameRequest()
926 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
927 _exit_game = true;
928 } else if (_settings_client.gui.autosave_on_exit) {
929 DoExitSave();
930 _exit_game = true;
931 } else {
932 AskExitGame();
936 static void MakeNewGameDone()
938 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
940 /* In a dedicated server, the server does not play */
941 if (!_video_driver->HasGUI()) {
942 SetLocalCompany(COMPANY_SPECTATOR);
943 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
944 IConsoleCmdExec("exec scripts/game_start.scr 0");
945 return;
948 /* Create a single company */
949 DoStartupNewCompany(false);
951 Company *c = Company::Get(COMPANY_FIRST);
952 c->settings = _settings_client.company;
954 IConsoleCmdExec("exec scripts/game_start.scr 0");
956 SetLocalCompany(COMPANY_FIRST);
958 InitializeRailGUI();
960 #ifdef ENABLE_NETWORK
961 /* We are the server, we start a new company (not dedicated),
962 * so set the default password *if* needed. */
963 if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
964 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
966 #endif /* ENABLE_NETWORK */
968 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
970 CheckEngines();
971 MarkWholeScreenDirty();
974 static void MakeNewGame(bool from_heightmap, bool reset_settings)
976 _game_mode = GM_NORMAL;
978 ResetGRFConfig(true);
980 GenerateWorldSetCallback(&MakeNewGameDone);
981 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
984 static void MakeNewEditorWorldDone()
986 SetLocalCompany(OWNER_NONE);
989 static void MakeNewEditorWorld()
991 _game_mode = GM_EDITOR;
993 ResetGRFConfig(true);
995 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
996 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1000 * Load the specified savegame but on error do different things.
1001 * If loading fails due to corrupt savegame, bad version, etc. go back to
1002 * a previous correct state. In the menu for example load the intro game again.
1003 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
1004 * @param newgm switch to this mode of loading fails due to some unknown error
1005 * @param filename file to be loaded
1006 * @param subdir default directory to look for filename, set to 0 if not needed
1007 * @param lf Load filter to use, if NULL: use filename + subdir.
1009 bool SafeLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
1011 assert(mode == SL_LOAD || (lf == NULL && mode == SL_OLD_LOAD));
1012 GameMode ogm = _game_mode;
1014 _game_mode = newgm;
1016 if (lf == NULL ? LoadGame(filename, mode, subdir) : LoadWithFilter(lf)) {
1017 return true;
1018 } else {
1019 #ifdef ENABLE_NETWORK
1020 if (_network_dedicated) {
1022 * We need to reinit a network map...
1023 * We can't simply load the intro game here as that game has many
1024 * special cases which make clients desync immediately. So we fall
1025 * back to just generating a new game with the current settings.
1027 DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
1028 MakeNewGame(false, true);
1029 return false;
1031 if (_network_server) {
1032 /* We can't load the intro game as server, so disconnect first. */
1033 NetworkDisconnect();
1035 #endif /* ENABLE_NETWORK */
1037 switch (ogm) {
1038 default:
1039 case GM_MENU: LoadIntroGame(); break;
1040 case GM_EDITOR: MakeNewEditorWorld(); break;
1042 return false;
1046 void SwitchToMode(SwitchMode new_mode)
1048 #ifdef ENABLE_NETWORK
1049 /* If we are saving something, the network stays in his current state */
1050 if (new_mode != SM_SAVE_GAME) {
1051 /* If the network is active, make it not-active */
1052 if (_networking) {
1053 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1054 NetworkReboot();
1055 } else {
1056 NetworkDisconnect();
1060 /* If we are a server, we restart the server */
1061 if (_is_network_server) {
1062 /* But not if we are going to the menu */
1063 if (new_mode != SM_MENU) {
1064 /* check if we should reload the config */
1065 if (_settings_client.network.reload_cfg) {
1066 LoadFromConfig();
1067 MakeNewgameSettingsLive();
1068 ResetGRFConfig(false);
1070 NetworkServerStart();
1071 } else {
1072 /* This client no longer wants to be a network-server */
1073 _is_network_server = false;
1077 #endif /* ENABLE_NETWORK */
1078 /* Make sure all AI controllers are gone at quitting game */
1079 if (new_mode != SM_SAVE_GAME) AI::KillAll();
1081 switch (new_mode) {
1082 case SM_EDITOR: // Switch to scenario editor
1083 MakeNewEditorWorld();
1084 break;
1086 case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1087 case SM_NEWGAME: // New Game --> 'Random game'
1088 #ifdef ENABLE_NETWORK
1089 if (_network_server) {
1090 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
1092 #endif /* ENABLE_NETWORK */
1093 MakeNewGame(false, new_mode == SM_NEWGAME);
1094 break;
1096 case SM_LOAD_GAME: { // Load game, Play Scenario
1097 ResetGRFConfig(true);
1098 ResetWindowSystem();
1100 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
1101 SetDParamStr(0, GetSaveLoadErrorString());
1102 ShowErrorMessage(STR_ERROR_GAME_LOAD_FAILED, STR_JUST_RAW_STRING, WL_ERROR);
1103 } else {
1104 if (_saveload_mode == SLD_LOAD_SCENARIO) {
1105 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1106 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1108 /* Update the local company for a loaded game. It is either always
1109 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1110 SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
1111 /* Execute the game-start script */
1112 IConsoleCmdExec("exec scripts/game_start.scr 0");
1113 /* Decrease pause counter (was increased from opening load dialog) */
1114 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1115 #ifdef ENABLE_NETWORK
1116 if (_network_server) {
1117 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
1119 #endif /* ENABLE_NETWORK */
1121 break;
1124 case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1125 #ifdef ENABLE_NETWORK
1126 if (_network_server) {
1127 snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
1129 #endif /* ENABLE_NETWORK */
1130 MakeNewGame(true, true);
1131 break;
1133 case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1134 SetLocalCompany(OWNER_NONE);
1136 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1137 MarkWholeScreenDirty();
1138 break;
1140 case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1141 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
1142 SetLocalCompany(OWNER_NONE);
1143 _settings_newgame.game_creation.starting_year = _cur_year;
1144 /* Cancel the saveload pausing */
1145 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1146 } else {
1147 SetDParamStr(0, GetSaveLoadErrorString());
1148 ShowErrorMessage(STR_ERROR_GAME_LOAD_FAILED, STR_JUST_RAW_STRING, WL_ERROR);
1150 break;
1153 case SM_MENU: // Switch to game intro menu
1154 LoadIntroGame();
1155 if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
1156 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1157 BaseSounds::ini_set = strdup(BaseSounds::GetUsedSet()->name);
1159 break;
1161 case SM_SAVE_GAME: // Save game.
1162 /* Make network saved games on pause compatible to singleplayer */
1163 if (!SaveGame(_file_to_saveload.name, NO_DIRECTORY)) {
1164 SetDParamStr(0, GetSaveLoadErrorString());
1165 ShowErrorMessage(STR_ERROR_GAME_SAVE_FAILED, STR_JUST_RAW_STRING, WL_ERROR);
1166 } else {
1167 DeleteWindowById(WC_SAVELOAD, 0);
1169 break;
1171 case SM_SAVE_HEIGHTMAP: // Save heightmap.
1172 MakeHeightmapScreenshot(_file_to_saveload.name);
1173 DeleteWindowById(WC_SAVELOAD, 0);
1174 break;
1176 case SM_GENRANDLAND: // Generate random land within scenario editor
1177 SetLocalCompany(OWNER_NONE);
1178 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1179 /* XXX: set date */
1180 MarkWholeScreenDirty();
1181 break;
1183 default: NOT_REACHED();
1189 * Check the validity of some of the caches.
1190 * Especially in the sense of desyncs between
1191 * the cached value and what the value would
1192 * be when calculated from the 'base' data.
1194 static void CheckCaches()
1196 /* Return here so it is easy to add checks that are run
1197 * always to aid testing of caches. */
1198 if (_debug_desync_level <= 1) return;
1200 /* Check the town caches. */
1201 SmallVector<TownCache, 4> old_town_caches;
1202 Town *t;
1203 FOR_ALL_TOWNS(t) {
1204 MemCpyT(old_town_caches.Append(), &t->cache);
1207 extern void RebuildTownCaches();
1208 RebuildTownCaches();
1209 RebuildSubsidisedSourceAndDestinationCache();
1211 uint i = 0;
1212 FOR_ALL_TOWNS(t) {
1213 if (MemCmpT(old_town_caches.Get(i), &t->cache) != 0) {
1214 DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
1216 i++;
1219 /* Check company infrastructure cache. */
1220 SmallVector<CompanyInfrastructure, 4> old_infrastructure;
1221 Company *c;
1222 FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
1224 extern void AfterLoadCompanyStats();
1225 AfterLoadCompanyStats();
1227 i = 0;
1228 FOR_ALL_COMPANIES(c) {
1229 if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
1230 DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
1232 i++;
1235 /* Strict checking of the road stop cache entries */
1236 const RoadStop *rs;
1237 FOR_ALL_ROADSTOPS(rs) {
1238 if (IsStandardRoadStopTile(rs->xy)) continue;
1240 assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
1241 rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
1242 rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
1245 Vehicle *v;
1246 FOR_ALL_VEHICLES(v) {
1247 extern void FillNewGRFVehicleCache(const Vehicle *v);
1248 if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1250 uint length = 0;
1251 for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
1253 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1254 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1255 GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
1256 TrainCache *tra_cache = CallocT<TrainCache>(length);
1258 length = 0;
1259 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1260 FillNewGRFVehicleCache(u);
1261 grf_cache[length] = u->grf_cache;
1262 veh_cache[length] = u->vcache;
1263 switch (u->type) {
1264 case VEH_TRAIN:
1265 gro_cache[length] = Train::From(u)->gcache;
1266 tra_cache[length] = Train::From(u)->tcache;
1267 break;
1268 case VEH_ROAD:
1269 gro_cache[length] = RoadVehicle::From(u)->gcache;
1270 break;
1271 default:
1272 break;
1274 length++;
1277 switch (v->type) {
1278 case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
1279 case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
1280 case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
1281 case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
1282 default: break;
1285 length = 0;
1286 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1287 FillNewGRFVehicleCache(u);
1288 if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1289 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);
1291 if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1292 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);
1294 switch (u->type) {
1295 case VEH_TRAIN:
1296 if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1297 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);
1299 if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1300 DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1302 break;
1303 case VEH_ROAD:
1304 if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1305 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);
1307 break;
1308 default:
1309 break;
1311 length++;
1314 free(grf_cache);
1315 free(veh_cache);
1316 free(gro_cache);
1317 free(tra_cache);
1320 /* Check whether the caches are still valid */
1321 FOR_ALL_VEHICLES(v) {
1322 byte buff[sizeof(VehicleCargoList)];
1323 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1324 v->cargo.InvalidateCache();
1325 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1328 Station *st;
1329 FOR_ALL_STATIONS(st) {
1330 for (CargoID c = 0; c < NUM_CARGO; c++) {
1331 byte buff[sizeof(StationCargoList)];
1332 memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
1333 st->goods[c].cargo.InvalidateCache();
1334 assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
1340 * State controlling game loop.
1341 * The state must not be changed from anywhere but here.
1342 * That check is enforced in DoCommand.
1344 void StateGameLoop()
1346 /* don't execute the state loop during pause */
1347 if (_pause_mode != PM_UNPAUSED) {
1348 UpdateLandscapingLimits();
1349 #ifndef DEBUG_DUMP_COMMANDS
1350 Game::GameLoop();
1351 #endif
1352 CallWindowTickEvent();
1353 return;
1355 if (HasModalProgress()) return;
1357 Layouter::ReduceLineCache();
1359 if (_game_mode == GM_EDITOR) {
1360 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1361 RunTileLoop();
1362 CallVehicleTicks();
1363 CallLandscapeTick();
1364 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1365 UpdateLandscapingLimits();
1367 CallWindowTickEvent();
1368 NewsLoop();
1369 } else {
1370 if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
1371 /* Save the desync savegame if needed. */
1372 char name[MAX_PATH];
1373 snprintf(name, lengthof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
1374 SaveGame(name, AUTOSAVE_DIR, false);
1377 CheckCaches();
1379 /* All these actions has to be done from OWNER_NONE
1380 * for multiplayer compatibility */
1381 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1383 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1384 AnimateAnimatedTiles();
1385 IncreaseDate();
1386 RunTileLoop();
1387 CallVehicleTicks();
1388 CallLandscapeTick();
1389 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1391 #ifndef DEBUG_DUMP_COMMANDS
1392 AI::GameLoop();
1393 Game::GameLoop();
1394 #endif
1395 UpdateLandscapingLimits();
1397 CallWindowTickEvent();
1398 NewsLoop();
1399 cur_company.Restore();
1402 assert(IsLocalCompany());
1406 * Create an autosave. The default name is "autosave#.sav". However with
1407 * the setting 'keep_all_autosave' the name defaults to company-name + date
1409 static void DoAutosave()
1411 char buf[MAX_PATH];
1413 #if defined(PSP)
1414 /* Autosaving in networking is too time expensive for the PSP */
1415 if (_networking) return;
1416 #endif /* PSP */
1418 if (_settings_client.gui.keep_all_autosave) {
1419 GenerateDefaultSaveName(buf, lastof(buf));
1420 strecat(buf, ".sav", lastof(buf));
1421 } else {
1422 static int _autosave_ctr = 0;
1424 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1425 snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
1427 if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
1430 DEBUG(sl, 2, "Autosaving to '%s'", buf);
1431 if (!SaveGame(buf, AUTOSAVE_DIR)) {
1432 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
1436 void GameLoop()
1438 if (_game_mode == GM_BOOTSTRAP) {
1439 #ifdef ENABLE_NETWORK
1440 /* Check for UDP stuff */
1441 if (_network_available) NetworkBackgroundLoop();
1442 #endif
1443 InputLoop();
1444 return;
1447 ProcessAsyncSaveFinish();
1449 /* autosave game? */
1450 if (_do_autosave) {
1451 DoAutosave();
1452 _do_autosave = false;
1453 SetWindowDirty(WC_STATUS_BAR, 0);
1456 /* switch game mode? */
1457 if (_switch_mode != SM_NONE && !HasModalProgress()) {
1458 SwitchToMode(_switch_mode);
1459 _switch_mode = SM_NONE;
1462 IncreaseSpriteLRU();
1463 InteractiveRandom();
1465 extern int _caret_timer;
1466 _caret_timer += 3;
1467 CursorTick();
1469 #ifdef ENABLE_NETWORK
1470 /* Check for UDP stuff */
1471 if (_network_available) NetworkBackgroundLoop();
1473 if (_networking && !HasModalProgress()) {
1474 /* Multiplayer */
1475 NetworkGameLoop();
1476 } else {
1477 if (_network_reconnect > 0 && --_network_reconnect == 0) {
1478 /* This means that we want to reconnect to the last host
1479 * We do this here, because it means that the network is really closed */
1480 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
1482 /* Singleplayer */
1483 StateGameLoop();
1486 /* Check chat messages roughly once a second. */
1487 static uint check_message = 0;
1488 if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
1489 check_message = 0;
1490 NetworkChatMessageLoop();
1492 #else
1493 StateGameLoop();
1494 #endif /* ENABLE_NETWORK */
1496 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1498 if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
1500 InputLoop();
1502 _sound_driver->MainLoop();
1503 MusicLoop();