Maintain a circular buffer of recent commands, add to crashlog.
[openttd-joker.git] / src / openttd.cpp
blobd1509730eaa324aa1362e690ba7b1d10a897043c
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 "newgrf_commons.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 "viewport_sprite_sorter.h"
67 #include "smallmap_gui.h"
68 #include "viewport_func.h"
69 #include "bridge_signal_map.h"
71 #include "linkgraph/linkgraphschedule.h"
72 #include "tracerestrict.h"
74 #include <stdarg.h>
76 #include "safeguards.h"
78 void CallLandscapeTick();
79 void IncreaseDate();
80 void DoPaletteAnimations();
81 void MusicLoop();
82 void ResetMusic();
83 void CallWindowTickEvent();
84 bool HandleBootstrap();
86 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
87 extern void ShowOSErrorBox(const char *buf, bool system);
88 extern char *_config_file;
90 /**
91 * Error handling for fatal user errors.
92 * @param s the string to print.
93 * @note Does NEVER return.
95 void CDECL usererror(const char *s, ...)
97 va_list va;
98 char buf[512];
100 va_start(va, s);
101 vseprintf(buf, lastof(buf), s, va);
102 va_end(va);
104 ShowOSErrorBox(buf, false);
105 if (VideoDriver::GetInstance() != NULL) VideoDriver::GetInstance()->Stop();
107 exit(1);
111 * Error handling for fatal non-user errors.
112 * @param s the string to print.
113 * @note Does NEVER return.
115 void CDECL error(const char *s, ...)
117 va_list va;
118 char buf[512];
120 va_start(va, s);
121 vseprintf(buf, lastof(buf), s, va);
122 va_end(va);
124 ShowOSErrorBox(buf, true);
126 /* Set the error message for the crash log and then invoke it. */
127 CrashLog::SetErrorMessage(buf);
128 abort();
131 void CDECL assert_msg_error(int line, const char *file, const char *expr, const char *str, ...)
133 va_list va;
134 char buf[2048];
136 char *b = buf;
137 b += seprintf(b, lastof(buf), "Assertion failed at line %i of %s: %s\n\t", line, file, expr);
139 va_start(va, str);
140 vseprintf(b, lastof(buf), str, va);
141 va_end(va);
143 ShowOSErrorBox(buf, true);
145 /* Set the error message for the crash log and then invoke it. */
146 CrashLog::SetErrorMessage(buf);
147 abort();
151 * Shows some information on the console/a popup box depending on the OS.
152 * @param str the text to show.
154 void CDECL ShowInfoF(const char *str, ...)
156 va_list va;
157 char buf[1024];
158 va_start(va, str);
159 vseprintf(buf, lastof(buf), str, va);
160 va_end(va);
161 ShowInfo(buf);
165 * Show the help message when someone passed a wrong parameter.
167 static void ShowHelp()
169 char buf[8192];
170 char *p = buf;
172 p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
173 p = strecpy(p,
174 "\n"
175 "\n"
176 "Command line options:\n"
177 " -v drv = Set video driver (see below)\n"
178 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
179 " -m drv = Set music driver (see below)\n"
180 " -b drv = Set the blitter to use (see below)\n"
181 " -r res = Set resolution (for instance 800x600)\n"
182 " -h = Display this help text\n"
183 " -t year = Set starting year\n"
184 " -d [[fac=]lvl[,...]]= Debug mode\n"
185 " -e = Start Editor\n"
186 " -g [savegame] = Start new/save game immediately\n"
187 " -G seed = Set random seed\n"
188 #if defined(ENABLE_NETWORK)
189 " -n [ip:port#company]= Join network game\n"
190 " -p password = Password to join server\n"
191 " -P password = Password to join company\n"
192 " -D [ip][:port] = Start dedicated server\n"
193 " -l ip[:port] = Redirect DEBUG()\n"
194 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
195 " -f = Fork into the background (dedicated only)\n"
196 #endif
197 #endif /* ENABLE_NETWORK */
198 " -I graphics_set = Force the graphics set (see below)\n"
199 " -S sounds_set = Force the sounds set (see below)\n"
200 " -M music_set = Force the music set (see below)\n"
201 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
202 " -x = Do not automatically save to config file on exit\n"
203 " -q savegame = Write some information about the savegame and exit\n"
204 "\n",
205 lastof(buf)
208 /* List the graphics packs */
209 p = BaseGraphics::GetSetsList(p, lastof(buf));
211 /* List the sounds packs */
212 p = BaseSounds::GetSetsList(p, lastof(buf));
214 /* List the music packs */
215 p = BaseMusic::GetSetsList(p, lastof(buf));
217 /* List the drivers */
218 p = DriverFactoryBase::GetDriversInfo(p, lastof(buf));
220 /* List the blitters */
221 p = BlitterFactory::GetBlittersInfo(p, lastof(buf));
223 /* List the debug facilities. */
224 p = DumpDebugFacilityNames(p, lastof(buf));
226 /* We need to initialize the AI, so it finds the AIs */
227 AI::Initialize();
228 p = AI::GetConsoleList(p, lastof(buf), true);
229 AI::Uninitialize(true);
231 /* We need to initialize the GameScript, so it finds the GSs */
232 Game::Initialize();
233 p = Game::GetConsoleList(p, lastof(buf), true);
234 Game::Uninitialize(true);
236 /* ShowInfo put output to stderr, but version information should go
237 * to stdout; this is the only exception */
238 #if !defined(WIN32) && !defined(WIN64)
239 printf("%s\n", buf);
240 #else
241 ShowInfo(buf);
242 #endif
245 static void WriteSavegameInfo(const char *name)
247 extern uint16 _sl_version;
248 uint32 last_ottd_rev = 0;
249 byte ever_modified = 0;
250 bool removed_newgrfs = false;
252 GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
254 char buf[8192];
255 char *p = buf;
256 p += seprintf(p, lastof(buf), "Name: %s\n", name);
257 p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
258 p += seprintf(p, lastof(buf), "NewGRF ver: 0x%08X\n", last_ottd_rev);
259 p += seprintf(p, lastof(buf), "Modified: %d\n", ever_modified);
261 if (removed_newgrfs) {
262 p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
265 p = strecpy(p, "NewGRFs:\n", lastof(buf));
266 if (_load_check_data.HasNewGrfs()) {
267 for (GRFConfig *c = _load_check_data.grfconfig; c != NULL; c = c->next) {
268 char md5sum[33];
269 md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
270 p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
274 /* ShowInfo put output to stderr, but version information should go
275 * to stdout; this is the only exception */
276 #if !defined(WIN32) && !defined(WIN64)
277 printf("%s\n", buf);
278 #else
279 ShowInfo(buf);
280 #endif
285 * Extract the resolution from the given string and store
286 * it in the 'res' parameter.
287 * @param res variable to store the resolution in.
288 * @param s the string to decompose.
290 static void ParseResolution(Dimension *res, const char *s)
292 const char *t = strchr(s, 'x');
293 if (t == NULL) {
294 ShowInfoF("Invalid resolution '%s'", s);
295 return;
298 res->width = max(strtoul(s, NULL, 0), 64UL);
299 res->height = max(strtoul(t + 1, NULL, 0), 64UL);
304 * Unitializes drivers, frees allocated memory, cleans pools, ...
305 * Generally, prepares the game for shutting down
307 static void ShutdownGame()
309 IConsoleFree();
311 if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
313 DriverFactoryBase::ShutdownDrivers();
315 UnInitWindowSystem();
317 /* stop the scripts */
318 AI::Uninitialize(false);
319 Game::Uninitialize(false);
321 /* Uninitialize variables that are allocated dynamically */
322 GamelogReset();
324 #ifdef ENABLE_NETWORK
325 free(_config_file);
326 #endif
328 LinkGraphSchedule::Clear();
329 ClearBridgeSimulatedSignalMapping();
330 ClearTraceRestrictMapping();
331 PoolBase::Clean(PT_ALL);
333 /* No NewGRFs were loaded when it was still bootstrapping. */
334 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
336 /* Close all and any open filehandles */
337 FioCloseAll();
339 UninitFreeType();
341 ClearCommandLog();
343 ViewportMapClearTunnelCache();
347 * Load the introduction game.
348 * @param load_newgrfs Whether to load the NewGRFs or not.
350 static void LoadIntroGame(bool load_newgrfs = true)
352 _game_mode = GM_MENU;
354 if (load_newgrfs) ResetGRFConfig(false);
356 /* Setup main window */
357 ResetWindowSystem();
358 SetupColoursAndInitialWindow();
360 /* Load the default opening screen savegame */
361 if (SaveOrLoad("opntitle.dat", SLO_LOAD, DFT_GAME_FILE, BASESET_DIR) != SL_OK) {
362 GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
363 WaitTillGeneratedWorld();
364 SetLocalCompany(COMPANY_SPECTATOR);
365 } else {
366 SetLocalCompany(COMPANY_FIRST);
369 _pause_mode = PM_UNPAUSED;
370 _cursor.fix_at = false;
372 CheckForMissingGlyphs();
374 /* Play main theme */
375 if (MusicDriver::GetInstance()->IsSongPlaying()) ResetMusic();
378 void MakeNewgameSettingsLive()
380 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
381 if (_settings_game.ai_config[c] != NULL) {
382 delete _settings_game.ai_config[c];
385 if (_settings_game.game_config != NULL) {
386 delete _settings_game.game_config;
389 /* Copy newgame settings to active settings.
390 * Also initialise old settings needed for savegame conversion. */
391 _settings_game = _settings_newgame;
392 _old_vds = _settings_client.company.vehicle;
394 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
395 _settings_game.ai_config[c] = NULL;
396 if (_settings_newgame.ai_config[c] != NULL) {
397 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
400 _settings_game.game_config = NULL;
401 if (_settings_newgame.game_config != NULL) {
402 _settings_game.game_config = new GameConfig(_settings_newgame.game_config);
406 void OpenBrowser(const char *url)
408 /* Make sure we only accept urls that are sure to open a browser. */
409 if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
411 extern void OSOpenBrowser(const char *url);
412 OSOpenBrowser(url);
415 /** Callback structure of statements to be executed after the NewGRF scan. */
416 struct AfterNewGRFScan : NewGRFScanCallback {
417 Year startyear; ///< The start year.
418 uint generation_seed; ///< Seed for the new game.
419 char *dedicated_host; ///< Hostname for the dedicated server.
420 uint16 dedicated_port; ///< Port for the dedicated server.
421 char *network_conn; ///< Information about the server to connect to, or NULL.
422 const char *join_server_password; ///< The password to join the server with.
423 const char *join_company_password; ///< The password to join the company with.
424 bool *save_config_ptr; ///< The pointer to the save config setting.
425 bool save_config; ///< The save config setting.
428 * Create a new callback.
429 * @param save_config_ptr Pointer to the save_config local variable which
430 * decides whether to save of exit or not.
432 AfterNewGRFScan(bool *save_config_ptr) :
433 startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
434 dedicated_host(NULL), dedicated_port(0), network_conn(NULL),
435 join_server_password(NULL), join_company_password(NULL),
436 save_config_ptr(save_config_ptr), save_config(true)
440 virtual void OnNewGRFsScanned()
442 ResetGRFConfig(false);
444 TarScanner::DoScan(TarScanner::SCENARIO);
446 AI::Initialize();
447 Game::Initialize();
449 /* We want the new (correct) NewGRF count to survive the loading. */
450 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
451 LoadFromConfig();
452 _settings_client.gui.last_newgrf_count = last_newgrf_count;
453 /* Since the default for the palette might have changed due to
454 * reading the configuration file, recalculate that now. */
455 UpdateNewGRFConfigPalette();
457 Game::Uninitialize(true);
458 AI::Uninitialize(true);
459 CheckConfig();
460 LoadFromHighScore();
461 LoadHotkeysFromConfig();
462 WindowDesc::LoadFromConfig();
464 /* We have loaded the config, so we may possibly save it. */
465 *save_config_ptr = save_config;
467 /* restore saved music volume */
468 MusicDriver::GetInstance()->SetVolume(_settings_client.music.music_vol);
470 if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
471 if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
473 #if defined(ENABLE_NETWORK)
474 if (dedicated_host != NULL) {
475 _network_bind_list.Clear();
476 *_network_bind_list.Append() = stredup(dedicated_host);
478 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
479 #endif /* ENABLE_NETWORK */
481 /* initialize the ingame console */
482 IConsoleInit();
483 InitializeGUI();
484 IConsoleCmdExec("exec scripts/autoexec.scr 0");
486 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
487 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
489 #ifdef ENABLE_NETWORK
490 if (_network_available && network_conn != NULL) {
491 const char *port = NULL;
492 const char *company = NULL;
493 uint16 rport = NETWORK_DEFAULT_PORT;
494 CompanyID join_as = COMPANY_NEW_COMPANY;
496 ParseConnectionString(&company, &port, network_conn);
498 if (company != NULL) {
499 join_as = (CompanyID)atoi(company);
501 if (join_as != COMPANY_SPECTATOR) {
502 join_as--;
503 if (join_as >= MAX_COMPANIES) {
504 delete this;
505 return;
509 if (port != NULL) rport = atoi(port);
511 LoadIntroGame();
512 _switch_mode = SM_NONE;
513 NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
515 #endif /* ENABLE_NETWORK */
517 /* After the scan we're not used anymore. */
518 delete this;
522 #if defined(UNIX) && !defined(__MORPHOS__)
523 extern void DedicatedFork();
524 #endif
526 /** Options of OpenTTD. */
527 static const OptionData _options[] = {
528 GETOPT_SHORT_VALUE('I'),
529 GETOPT_SHORT_VALUE('S'),
530 GETOPT_SHORT_VALUE('M'),
531 GETOPT_SHORT_VALUE('m'),
532 GETOPT_SHORT_VALUE('s'),
533 GETOPT_SHORT_VALUE('v'),
534 GETOPT_SHORT_VALUE('b'),
535 #if defined(ENABLE_NETWORK)
536 GETOPT_SHORT_OPTVAL('D'),
537 GETOPT_SHORT_OPTVAL('n'),
538 GETOPT_SHORT_VALUE('l'),
539 GETOPT_SHORT_VALUE('p'),
540 GETOPT_SHORT_VALUE('P'),
541 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
542 GETOPT_SHORT_NOVAL('f'),
543 #endif
544 #endif /* ENABLE_NETWORK */
545 GETOPT_SHORT_VALUE('r'),
546 GETOPT_SHORT_VALUE('t'),
547 GETOPT_SHORT_OPTVAL('d'),
548 GETOPT_SHORT_NOVAL('e'),
549 GETOPT_SHORT_OPTVAL('g'),
550 GETOPT_SHORT_VALUE('G'),
551 GETOPT_SHORT_VALUE('c'),
552 GETOPT_SHORT_NOVAL('x'),
553 GETOPT_SHORT_VALUE('q'),
554 GETOPT_SHORT_NOVAL('h'),
555 GETOPT_END()
559 * Main entry point for this lovely game.
560 * @param argc The number of arguments passed to this game.
561 * @param argv The values of the arguments.
562 * @return 0 when there is no error.
564 int openttd_main(int argc, char *argv[])
566 char *musicdriver = NULL;
567 char *sounddriver = NULL;
568 char *videodriver = NULL;
569 char *blitter = NULL;
570 char *graphics_set = NULL;
571 char *sounds_set = NULL;
572 char *music_set = NULL;
573 Dimension resolution = {0, 0};
574 /* AfterNewGRFScan sets save_config to true after scanning completed. */
575 bool save_config = false;
576 AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
577 #if defined(ENABLE_NETWORK)
578 bool dedicated = false;
579 char *debuglog_conn = NULL;
581 extern bool _dedicated_forks;
582 _dedicated_forks = false;
583 #endif /* ENABLE_NETWORK */
585 _game_mode = GM_MENU;
586 _switch_mode = SM_MENU;
587 _config_file = NULL;
589 GetOptData mgo(argc - 1, argv + 1, _options);
590 int ret = 0;
592 int i;
593 while ((i = mgo.GetOpt()) != -1) {
594 switch (i) {
595 case 'I': free(graphics_set); graphics_set = stredup(mgo.opt); break;
596 case 'S': free(sounds_set); sounds_set = stredup(mgo.opt); break;
597 case 'M': free(music_set); music_set = stredup(mgo.opt); break;
598 case 'm': free(musicdriver); musicdriver = stredup(mgo.opt); break;
599 case 's': free(sounddriver); sounddriver = stredup(mgo.opt); break;
600 case 'v': free(videodriver); videodriver = stredup(mgo.opt); break;
601 case 'b': free(blitter); blitter = stredup(mgo.opt); break;
602 #if defined(ENABLE_NETWORK)
603 case 'D':
604 free(musicdriver);
605 free(sounddriver);
606 free(videodriver);
607 free(blitter);
608 musicdriver = stredup("null");
609 sounddriver = stredup("null");
610 videodriver = stredup("dedicated");
611 blitter = stredup("null");
612 dedicated = true;
613 SetDebugString("net=6");
614 if (mgo.opt != NULL) {
615 /* Use the existing method for parsing (openttd -n).
616 * However, we do ignore the #company part. */
617 const char *temp = NULL;
618 const char *port = NULL;
619 ParseConnectionString(&temp, &port, mgo.opt);
620 if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
621 if (port != NULL) scanner->dedicated_port = atoi(port);
623 break;
624 case 'f': _dedicated_forks = true; break;
625 case 'n':
626 scanner->network_conn = mgo.opt; // optional IP parameter, NULL if unset
627 break;
628 case 'l':
629 debuglog_conn = mgo.opt;
630 break;
631 case 'p':
632 scanner->join_server_password = mgo.opt;
633 break;
634 case 'P':
635 scanner->join_company_password = mgo.opt;
636 break;
637 #endif /* ENABLE_NETWORK */
638 case 'r': ParseResolution(&resolution, mgo.opt); break;
639 case 't': scanner->startyear = atoi(mgo.opt); break;
640 case 'd': {
641 #if defined(WIN32)
642 CreateConsole();
643 #endif
644 if (mgo.opt != NULL) SetDebugString(mgo.opt);
645 break;
647 case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
648 case 'g':
649 if (mgo.opt != NULL) {
650 _file_to_saveload.SetName(mgo.opt);
651 bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
652 _switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
653 _file_to_saveload.SetMode(SLO_LOAD, is_scenario ? FT_SCENARIO : FT_SAVEGAME, DFT_GAME_FILE);
655 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
656 const char *t = strrchr(_file_to_saveload.name, '.');
657 if (t != NULL) {
658 FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, t, NULL, NULL);
659 if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
662 break;
665 _switch_mode = SM_NEWGAME;
666 /* Give a random map if no seed has been given */
667 if (scanner->generation_seed == GENERATE_NEW_SEED) {
668 scanner->generation_seed = InteractiveRandom();
670 break;
671 case 'q': {
672 DeterminePaths(argv[0]);
673 if (StrEmpty(mgo.opt)) {
674 ret = 1;
675 goto exit_noshutdown;
678 char title[80];
679 title[0] = '\0';
680 FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
682 _load_check_data.Clear();
683 SaveOrLoadResult res = SaveOrLoad(mgo.opt, SLO_CHECK, DFT_GAME_FILE, SAVE_DIR, false);
684 if (res != SL_OK || _load_check_data.HasErrors()) {
685 fprintf(stderr, "Failed to open savegame\n");
686 if (_load_check_data.HasErrors()) {
687 char buf[256];
688 SetDParamStr(0, _load_check_data.error_data);
689 GetString(buf, _load_check_data.error, lastof(buf));
690 fprintf(stderr, "%s\n", buf);
692 goto exit_noshutdown;
695 WriteSavegameInfo(title);
697 goto exit_noshutdown;
699 case 'G': scanner->generation_seed = atoi(mgo.opt); break;
700 case 'c': free(_config_file); _config_file = stredup(mgo.opt); break;
701 case 'x': scanner->save_config = false; break;
702 case 'h':
703 i = -2; // Force printing of help.
704 break;
706 if (i == -2) break;
709 if (i == -2 || mgo.numleft > 0) {
710 /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
711 * In all cases, print the help, and exit.
713 * The next two functions are needed to list the graphics sets. We can't do them earlier
714 * because then we cannot show it on the debug console as that hasn't been configured yet. */
715 DeterminePaths(argv[0]);
716 TarScanner::DoScan(TarScanner::BASESET);
717 BaseGraphics::FindSets();
718 BaseSounds::FindSets();
719 BaseMusic::FindSets();
720 ShowHelp();
722 goto exit_noshutdown;
725 #if defined(WINCE) && defined(_DEBUG)
726 /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
727 SetDebugString("4");
728 #endif
730 DeterminePaths(argv[0]);
731 TarScanner::DoScan(TarScanner::BASESET);
733 #if defined(ENABLE_NETWORK)
734 if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
735 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
737 #if defined(UNIX) && !defined(__MORPHOS__)
738 /* We must fork here, or we'll end up without some resources we need (like sockets) */
739 if (_dedicated_forks) DedicatedFork();
740 #endif
741 #endif
743 LoadFromConfig(true);
745 if (resolution.width != 0) _cur_resolution = resolution;
748 * The width and height must be at least 1 pixel and width times
749 * height times bytes per pixel must still fit within a 32 bits
750 * integer, even for 32 bpp video modes. This way all internal
751 * drawing routines work correctly.
753 _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX / 2);
754 _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
756 /* Assume the cursor starts within the game as not all video drivers
757 * get an event that the cursor is within the window when it is opened.
758 * Saying the cursor is there makes no visible difference as it would
759 * just be out of the bounds of the window. */
760 _cursor.in_window = true;
762 /* enumerate language files */
763 InitializeLanguagePacks();
765 /* Initialize the regular font for FreeType */
766 InitFreeType(false);
768 /* This must be done early, since functions use the SetWindowDirty* calls */
769 InitWindowSystem();
771 BaseGraphics::FindSets();
772 if (graphics_set == NULL && BaseGraphics::ini_set != NULL) graphics_set = stredup(BaseGraphics::ini_set);
773 if (!BaseGraphics::SetSet(graphics_set)) {
774 if (!StrEmpty(graphics_set)) {
775 BaseGraphics::SetSet(NULL);
777 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
778 msg.SetDParamStr(0, graphics_set);
779 ScheduleErrorMessage(msg);
782 free(graphics_set);
784 /* Initialize game palette */
785 GfxInitPalettes();
787 DEBUG(misc, 1, "Loading blitter...");
788 if (blitter == NULL && _ini_blitter != NULL) blitter = stredup(_ini_blitter);
789 _blitter_autodetected = StrEmpty(blitter);
790 /* Activate the initial blitter.
791 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
792 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
793 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
794 * - Use 8bpp blitter otherwise.
796 if (!_blitter_autodetected ||
797 (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == NULL || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
798 BlitterFactory::SelectBlitter("32bpp-anim") == NULL) {
799 if (BlitterFactory::SelectBlitter(blitter) == NULL) {
800 StrEmpty(blitter) ?
801 usererror("Failed to autoprobe blitter") :
802 usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
805 free(blitter);
807 if (videodriver == NULL && _ini_videodriver != NULL) videodriver = stredup(_ini_videodriver);
808 DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
809 free(videodriver);
811 InitializeSpriteSorter();
813 /* Initialize the zoom level of the screen to normal */
814 _screen.zoom = ZOOM_LVL_NORMAL;
816 NetworkStartUp(); // initialize network-core
818 #if defined(ENABLE_NETWORK)
819 if (debuglog_conn != NULL && _network_available) {
820 const char *not_used = NULL;
821 const char *port = NULL;
822 uint16 rport;
824 rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
826 ParseConnectionString(&not_used, &port, debuglog_conn);
827 if (port != NULL) rport = atoi(port);
829 NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
831 #endif /* ENABLE_NETWORK */
833 if (!HandleBootstrap()) {
834 ShutdownGame();
836 goto exit_bootstrap;
839 VideoDriver::GetInstance()->ClaimMousePointer();
841 /* initialize screenshot formats */
842 InitializeScreenshotFormats();
844 BaseSounds::FindSets();
845 if (sounds_set == NULL && BaseSounds::ini_set != NULL) sounds_set = stredup(BaseSounds::ini_set);
846 if (!BaseSounds::SetSet(sounds_set)) {
847 if (StrEmpty(sounds_set) || !BaseSounds::SetSet(NULL)) {
848 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
849 } else {
850 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
851 msg.SetDParamStr(0, sounds_set);
852 ScheduleErrorMessage(msg);
855 free(sounds_set);
857 BaseMusic::FindSets();
858 if (music_set == NULL && BaseMusic::ini_set != NULL) music_set = stredup(BaseMusic::ini_set);
859 if (!BaseMusic::SetSet(music_set)) {
860 if (StrEmpty(music_set) || !BaseMusic::SetSet(NULL)) {
861 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
862 } else {
863 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
864 msg.SetDParamStr(0, music_set);
865 ScheduleErrorMessage(msg);
868 free(music_set);
870 if (sounddriver == NULL && _ini_sounddriver != NULL) sounddriver = stredup(_ini_sounddriver);
871 DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
872 free(sounddriver);
874 if (musicdriver == NULL && _ini_musicdriver != NULL) musicdriver = stredup(_ini_musicdriver);
875 DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
876 free(musicdriver);
878 // Check if not too much GRFs are loaded for network game
879 if (dedicated && CountSelectedGRFs( _grfconfig ) > NETWORK_MAX_GRF_COUNT) {
880 DEBUG(net, 0, "Too many GRF loaded. Max %d are allowed.\nExiting ...", NETWORK_MAX_GRF_COUNT);
881 ShutdownGame();
882 goto exit_normal;
885 /* Take our initial lock on whatever we might want to do! */
886 _modal_progress_paint_mutex->BeginCritical();
887 _modal_progress_work_mutex->BeginCritical();
889 GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
890 WaitTillGeneratedWorld();
892 LoadIntroGame(false);
894 CheckForMissingGlyphs();
896 /* ScanNewGRFFiles now has control over the scanner. */
897 ScanNewGRFFiles(scanner);
898 scanner = NULL;
900 VideoDriver::GetInstance()->MainLoop();
902 WaitTillSaved();
904 /* only save config if we have to */
905 if (save_config) {
906 SaveToConfig();
907 SaveHotkeysToConfig();
908 WindowDesc::SaveToConfig();
909 SaveToHighScore();
912 /* Reset windowing system, stop drivers, free used memory, ... */
913 ShutdownGame();
914 goto exit_normal;
916 exit_noshutdown:
917 /* These three are normally freed before bootstrap. */
918 free(graphics_set);
919 free(videodriver);
920 free(blitter);
922 exit_bootstrap:
923 /* These are normally freed before exit, but after bootstrap. */
924 free(sounds_set);
925 free(music_set);
926 free(musicdriver);
927 free(sounddriver);
929 exit_normal:
930 free(BaseGraphics::ini_set);
931 free(BaseSounds::ini_set);
932 free(BaseMusic::ini_set);
934 free(_ini_musicdriver);
935 free(_ini_sounddriver);
936 free(_ini_videodriver);
937 free(_ini_blitter);
939 delete scanner;
941 #ifdef ENABLE_NETWORK
942 extern FILE *_log_fd;
943 if (_log_fd != NULL) {
944 fclose(_log_fd);
946 #endif /* ENABLE_NETWORK */
948 return ret;
951 void HandleExitGameRequest()
953 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
954 _exit_game = true;
955 } else if (_settings_client.gui.autosave_on_exit) {
956 DoExitSave();
957 _exit_game = true;
958 } else {
959 AskExitGame();
963 static void MakeNewGameDone()
965 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
967 extern void PostCheckNewGRFLoadWarnings();
968 PostCheckNewGRFLoadWarnings();
970 /* In a dedicated server, the server does not play */
971 if (!VideoDriver::GetInstance()->HasGUI()) {
972 SetLocalCompany(COMPANY_SPECTATOR);
973 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
974 IConsoleCmdExec("exec scripts/game_start.scr 0");
975 return;
978 /* Create a single company */
979 DoStartupNewCompany(false);
981 Company *c = Company::Get(COMPANY_FIRST);
982 c->settings = _settings_client.company;
984 IConsoleCmdExec("exec scripts/game_start.scr 0");
986 SetLocalCompany(COMPANY_FIRST);
988 InitializeRailGUI();
990 #ifdef ENABLE_NETWORK
991 /* We are the server, we start a new company (not dedicated),
992 * so set the default password *if* needed. */
993 if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
994 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
996 #endif /* ENABLE_NETWORK */
998 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
1000 CheckEngines();
1001 CheckIndustries();
1002 MarkWholeScreenDirty();
1005 static void MakeNewGame(bool from_heightmap, bool reset_settings)
1007 _game_mode = GM_NORMAL;
1009 ResetGRFConfig(true);
1011 GenerateWorldSetCallback(&MakeNewGameDone);
1012 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
1015 static void MakeNewEditorWorldDone()
1017 SetLocalCompany(OWNER_NONE);
1019 extern void PostCheckNewGRFLoadWarnings();
1020 PostCheckNewGRFLoadWarnings();
1023 static void MakeNewEditorWorld()
1025 _game_mode = GM_EDITOR;
1027 ResetGRFConfig(true);
1029 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
1030 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1034 * Load the specified savegame but on error do different things.
1035 * If loading fails due to corrupt savegame, bad version, etc. go back to
1036 * a previous correct state. In the menu for example load the intro game again.
1037 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
1038 * @param newgm switch to this mode of loading fails due to some unknown error
1039 * @param filename file to be loaded
1040 * @param subdir default directory to look for filename, set to 0 if not needed
1041 * @param lf Load filter to use, if NULL: use filename + subdir.
1043 bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL)
1045 assert(fop == SLO_LOAD);
1046 assert(dft == DFT_GAME_FILE || (lf == NULL && dft == DFT_OLD_GAME_FILE));
1047 GameMode ogm = _game_mode;
1049 _game_mode = newgm;
1051 switch (lf == NULL ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
1052 case SL_OK: return true;
1054 case SL_REINIT:
1055 #ifdef ENABLE_NETWORK
1056 if (_network_dedicated) {
1058 * We need to reinit a network map...
1059 * We can't simply load the intro game here as that game has many
1060 * special cases which make clients desync immediately. So we fall
1061 * back to just generating a new game with the current settings.
1063 DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
1064 MakeNewGame(false, true);
1065 return false;
1067 if (_network_server) {
1068 /* We can't load the intro game as server, so disconnect first. */
1069 NetworkDisconnect();
1071 #endif /* ENABLE_NETWORK */
1073 switch (ogm) {
1074 default:
1075 case GM_MENU: LoadIntroGame(); break;
1076 case GM_EDITOR: MakeNewEditorWorld(); break;
1078 return false;
1080 default:
1081 _game_mode = ogm;
1082 return false;
1086 void SwitchToMode(SwitchMode new_mode)
1088 #ifdef ENABLE_NETWORK
1089 /* If we are saving something, the network stays in his current state */
1090 if (new_mode != SM_SAVE_GAME) {
1091 /* If the network is active, make it not-active */
1092 if (_networking) {
1093 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1094 NetworkReboot();
1095 } else {
1096 NetworkDisconnect();
1100 /* If we are a server, we restart the server */
1101 if (_is_network_server) {
1102 /* But not if we are going to the menu */
1103 if (new_mode != SM_MENU) {
1104 /* check if we should reload the config */
1105 if (_settings_client.network.reload_cfg) {
1106 LoadFromConfig();
1107 MakeNewgameSettingsLive();
1108 ResetGRFConfig(false);
1110 NetworkServerStart();
1111 } else {
1112 /* This client no longer wants to be a network-server */
1113 _is_network_server = false;
1117 #endif /* ENABLE_NETWORK */
1118 /* Make sure all AI controllers are gone at quitting game */
1119 if (new_mode != SM_SAVE_GAME) AI::KillAll();
1121 switch (new_mode) {
1122 case SM_EDITOR: // Switch to scenario editor
1123 MakeNewEditorWorld();
1124 break;
1126 case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1127 case SM_NEWGAME: // New Game --> 'Random game'
1128 #ifdef ENABLE_NETWORK
1129 if (_network_server) {
1130 seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "Random Map");
1132 #endif /* ENABLE_NETWORK */
1133 MakeNewGame(false, new_mode == SM_NEWGAME);
1134 break;
1136 case SM_LOAD_GAME: { // Load game, Play Scenario
1137 ResetGRFConfig(true);
1138 ResetWindowSystem();
1140 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, NO_DIRECTORY)) {
1141 SetDParamStr(0, GetSaveLoadErrorString());
1142 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1143 } else {
1144 if (_file_to_saveload.abstract_ftype == FT_SCENARIO) {
1145 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1146 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1148 /* Update the local company for a loaded game. It is either always
1149 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1150 SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
1152 if (_ctrl_pressed && !_network_dedicated) {
1153 DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
1156 /* Execute the game-start script */
1157 IConsoleCmdExec("exec scripts/game_start.scr 0");
1158 /* Decrease pause counter (was increased from opening load dialog) */
1159 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1160 #ifdef ENABLE_NETWORK
1161 if (_network_server) {
1162 seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
1164 #endif /* ENABLE_NETWORK */
1166 break;
1169 case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1170 #ifdef ENABLE_NETWORK
1171 if (_network_server) {
1172 seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
1174 #endif /* ENABLE_NETWORK */
1175 MakeNewGame(true, true);
1176 break;
1178 case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1179 SetLocalCompany(OWNER_NONE);
1181 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1182 MarkWholeScreenDirty();
1183 break;
1185 case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1186 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) {
1187 SetLocalCompany(OWNER_NONE);
1188 _settings_newgame.game_creation.starting_year = _cur_year;
1189 /* Cancel the saveload pausing */
1190 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1191 } else {
1192 SetDParamStr(0, GetSaveLoadErrorString());
1193 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1195 break;
1198 case SM_MENU: // Switch to game intro menu
1199 LoadIntroGame();
1200 if (BaseSounds::ini_set == NULL && BaseSounds::GetUsedSet()->fallback) {
1201 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1202 BaseSounds::ini_set = stredup(BaseSounds::GetUsedSet()->name);
1204 break;
1206 case SM_SAVE_GAME: // Save game.
1207 /* Make network saved games on pause compatible to singleplayer */
1208 if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
1209 SetDParamStr(0, GetSaveLoadErrorString());
1210 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1211 } else {
1212 DeleteWindowById(WC_SAVELOAD, 0);
1214 break;
1216 case SM_SAVE_HEIGHTMAP: // Save heightmap.
1217 MakeHeightmapScreenshot(_file_to_saveload.name);
1218 DeleteWindowById(WC_SAVELOAD, 0);
1219 break;
1221 case SM_GENRANDLAND: // Generate random land within scenario editor
1222 SetLocalCompany(OWNER_NONE);
1223 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1224 /* XXX: set date */
1225 MarkWholeScreenDirty();
1226 break;
1228 default: NOT_REACHED();
1231 SmallMapWindow::RebuildColourIndexIfNecessary();
1236 * Check the validity of some of the caches.
1237 * Especially in the sense of desyncs between
1238 * the cached value and what the value would
1239 * be when calculated from the 'base' data.
1241 static void CheckCaches()
1243 /* Return here so it is easy to add checks that are run
1244 * always to aid testing of caches. */
1245 if (_debug_desync_level <= 1) return;
1247 /* Check the town caches. */
1248 SmallVector<TownCache, 4> old_town_caches;
1249 Town *t;
1250 FOR_ALL_TOWNS(t) {
1251 MemCpyT(old_town_caches.Append(), &t->cache);
1254 extern void RebuildTownCaches();
1255 RebuildTownCaches();
1256 RebuildSubsidisedSourceAndDestinationCache();
1258 uint i = 0;
1259 FOR_ALL_TOWNS(t) {
1260 if (MemCmpT(old_town_caches.Get(i), &t->cache) != 0) {
1261 DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
1263 i++;
1266 /* Check company infrastructure cache. */
1267 SmallVector<CompanyInfrastructure, 4> old_infrastructure;
1268 Company *c;
1269 FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);
1271 extern void AfterLoadCompanyStats();
1272 AfterLoadCompanyStats();
1274 i = 0;
1275 FOR_ALL_COMPANIES(c) {
1276 if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
1277 DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
1279 i++;
1282 /* Strict checking of the road stop cache entries */
1283 const RoadStop *rs;
1284 FOR_ALL_ROADSTOPS(rs) {
1285 if (IsStandardRoadStopTile(rs->xy)) continue;
1287 assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
1288 rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
1289 rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
1292 Vehicle *v;
1293 FOR_ALL_VEHICLES(v) {
1294 extern void FillNewGRFVehicleCache(const Vehicle *v);
1295 if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1297 uint length = 0;
1298 for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;
1300 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1301 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1302 GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
1303 TrainCache *tra_cache = CallocT<TrainCache>(length);
1305 length = 0;
1306 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1307 FillNewGRFVehicleCache(u);
1308 grf_cache[length] = u->grf_cache;
1309 veh_cache[length] = u->vcache;
1310 switch (u->type) {
1311 case VEH_TRAIN:
1312 gro_cache[length] = Train::From(u)->gcache;
1313 tra_cache[length] = Train::From(u)->tcache;
1314 break;
1315 case VEH_ROAD:
1316 gro_cache[length] = RoadVehicle::From(u)->gcache;
1317 break;
1318 default:
1319 break;
1321 length++;
1324 switch (v->type) {
1325 case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
1326 case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
1327 case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
1328 case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
1329 default: break;
1332 length = 0;
1333 for (const Vehicle *u = v; u != NULL; u = u->Next()) {
1334 FillNewGRFVehicleCache(u);
1335 if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1336 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);
1338 if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1339 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);
1341 switch (u->type) {
1342 case VEH_TRAIN:
1343 if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1344 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);
1346 if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1347 DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1349 break;
1350 case VEH_ROAD:
1351 if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1352 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);
1354 break;
1355 default:
1356 break;
1358 length++;
1361 free(grf_cache);
1362 free(veh_cache);
1363 free(gro_cache);
1364 free(tra_cache);
1367 /* Check whether the caches are still valid */
1368 FOR_ALL_VEHICLES(v) {
1369 byte buff[sizeof(VehicleCargoList)];
1370 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1371 v->cargo.InvalidateCache();
1372 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1375 Station *st;
1376 FOR_ALL_STATIONS(st) {
1377 for (CargoID c = 0; c < NUM_CARGO; c++) {
1378 byte buff[sizeof(StationCargoList)];
1379 memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
1380 st->goods[c].cargo.InvalidateCache();
1381 assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
1387 * State controlling game loop.
1388 * The state must not be changed from anywhere but here.
1389 * That check is enforced in DoCommand.
1391 void StateGameLoop()
1393 if (!_networking || _network_server) {
1394 extern void StateGameLoop_LinkGraphPauseControl();
1395 StateGameLoop_LinkGraphPauseControl();
1398 /* don't execute the state loop during pause */
1399 if (_pause_mode != PM_UNPAUSED) {
1400 UpdateLandscapingLimits();
1401 #ifndef DEBUG_DUMP_COMMANDS
1402 Game::GameLoop();
1403 #endif
1404 CallWindowTickEvent();
1405 return;
1407 if (HasModalProgress()) return;
1409 Layouter::ReduceLineCache();
1411 if (_game_mode == GM_EDITOR) {
1412 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1413 RunTileLoop();
1414 CallVehicleTicks();
1415 CallLandscapeTick();
1416 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1417 UpdateLandscapingLimits();
1419 CallWindowTickEvent();
1420 NewsLoop();
1421 } else {
1422 if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
1423 /* Save the desync savegame if needed. */
1424 char name[MAX_PATH];
1425 seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
1426 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
1429 CheckCaches();
1431 /* All these actions has to be done from OWNER_NONE
1432 * for multiplayer compatibility */
1433 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1435 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1436 AnimateAnimatedTiles();
1437 IncreaseDate();
1438 RunTileLoop();
1439 CallVehicleTicks();
1440 CallLandscapeTick();
1441 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1443 #ifndef DEBUG_DUMP_COMMANDS
1444 AI::GameLoop();
1445 Game::GameLoop();
1446 #endif
1447 UpdateLandscapingLimits();
1449 CallWindowTickEvent();
1450 NewsLoop();
1451 cur_company.Restore();
1454 assert(IsLocalCompany());
1458 * Create an autosave. The default name is "autosave#.sav". However with
1459 * the setting 'keep_all_autosave' the name defaults to company-name + date
1461 static void DoAutosave()
1463 char buf[MAX_PATH];
1465 #if defined(PSP)
1466 /* Autosaving in networking is too time expensive for the PSP */
1467 if (_networking) return;
1468 #endif /* PSP */
1470 if (_settings_client.gui.keep_all_autosave) {
1471 GenerateDefaultSaveName(buf, lastof(buf));
1472 strecat(buf, ".sav", lastof(buf));
1473 } else {
1474 static int _autosave_ctr = 0;
1476 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1477 seprintf(buf, lastof(buf), "autosave%d.sav", _autosave_ctr);
1479 if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
1482 DEBUG(sl, 2, "Autosaving to '%s'", buf);
1483 if (SaveOrLoad(buf, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR) != SL_OK) {
1484 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
1488 void GameLoop()
1490 if (_game_mode == GM_BOOTSTRAP) {
1491 #ifdef ENABLE_NETWORK
1492 /* Check for UDP stuff */
1493 if (_network_available) NetworkBackgroundLoop();
1494 #endif
1495 InputLoop();
1496 return;
1499 ProcessAsyncSaveFinish();
1501 /* autosave game? */
1502 if (_do_autosave) {
1503 DoAutosave();
1504 _do_autosave = false;
1505 SetWindowDirty(WC_STATUS_BAR, 0);
1508 /* switch game mode? */
1509 if (_switch_mode != SM_NONE && !HasModalProgress()) {
1510 SwitchToMode(_switch_mode);
1511 _switch_mode = SM_NONE;
1514 IncreaseSpriteLRU();
1515 InteractiveRandom();
1517 extern int _caret_timer;
1518 _caret_timer += 3;
1519 CursorTick();
1521 #ifdef ENABLE_NETWORK
1522 /* Check for UDP stuff */
1523 if (_network_available) NetworkBackgroundLoop();
1525 if (_networking && !HasModalProgress()) {
1526 /* Multiplayer */
1527 NetworkGameLoop();
1528 } else {
1529 if (_network_reconnect > 0 && --_network_reconnect == 0) {
1530 /* This means that we want to reconnect to the last host
1531 * We do this here, because it means that the network is really closed */
1532 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
1534 /* Singleplayer */
1535 StateGameLoop();
1538 /* Check chat messages roughly once a second. */
1539 static uint check_message = 0;
1540 if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
1541 check_message = 0;
1542 NetworkChatMessageLoop();
1544 #else
1545 StateGameLoop();
1546 #endif /* ENABLE_NETWORK */
1548 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1550 if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
1552 InputLoop();
1554 SoundDriver::GetInstance()->MainLoop();
1555 MusicLoop();