Increase the number of road and tram subtypes to 32.
[openttd-joker.git] / src / openttd.cpp
blob0e639efeee6e7933273abdbc43799b06c41d936d
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 "road_gui.h"
57 #include "core/backup_type.hpp"
58 #include "hotkeys.h"
59 #include "newgrf.h"
60 #include "newgrf_commons.h"
61 #include "misc/getoptdata.h"
62 #include "game/game.hpp"
63 #include "game/game_config.hpp"
64 #include "town.h"
65 #include "subsidy_func.h"
66 #include "gfx_layout.h"
67 #include "viewport_sprite_sorter.h"
68 #include "smallmap_gui.h"
69 #include "viewport_func.h"
70 #include "bridge_signal_map.h"
71 #include "zoning.h"
73 #include "linkgraph/linkgraphschedule.h"
74 #include "tracerestrict.h"
76 #include <stdarg.h>
78 #include "safeguards.h"
80 void CallLandscapeTick();
81 void IncreaseDate();
82 void DoPaletteAnimations();
83 void MusicLoop();
84 void ResetMusic();
85 void CallWindowTickEvent();
86 bool HandleBootstrap();
88 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
89 extern void ShowOSErrorBox(const char *buf, bool system);
90 extern char *_config_file;
92 /**
93 * Error handling for fatal user errors.
94 * @param s the string to print.
95 * @note Does NEVER return.
97 void CDECL usererror(const char *s, ...)
99 va_list va;
100 char buf[512];
102 va_start(va, s);
103 vseprintf(buf, lastof(buf), s, va);
104 va_end(va);
106 ShowOSErrorBox(buf, false);
107 if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
109 exit(1);
113 * Error handling for fatal non-user errors.
114 * @param s the string to print.
115 * @note Does NEVER return.
117 void CDECL error(const char *s, ...)
119 va_list va;
120 char buf[512];
122 va_start(va, s);
123 vseprintf(buf, lastof(buf), s, va);
124 va_end(va);
126 ShowOSErrorBox(buf, true);
128 /* Set the error message for the crash log and then invoke it. */
129 CrashLog::SetErrorMessage(buf);
130 abort();
133 void CDECL assert_msg_error(int line, const char *file, const char *expr, const char *str, ...)
135 va_list va;
136 char buf[2048];
138 char *b = buf;
139 b += seprintf(b, lastof(buf), "Assertion failed at line %i of %s: %s\n\t", line, file, expr);
141 va_start(va, str);
142 vseprintf(b, lastof(buf), str, va);
143 va_end(va);
145 ShowOSErrorBox(buf, true);
147 /* Set the error message for the crash log and then invoke it. */
148 CrashLog::SetErrorMessage(buf);
149 abort();
153 * Shows some information on the console/a popup box depending on the OS.
154 * @param str the text to show.
156 void CDECL ShowInfoF(const char *str, ...)
158 va_list va;
159 char buf[1024];
160 va_start(va, str);
161 vseprintf(buf, lastof(buf), str, va);
162 va_end(va);
163 ShowInfo(buf);
167 * Show the help message when someone passed a wrong parameter.
169 static void ShowHelp()
171 char buf[8192];
172 char *p = buf;
174 p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
175 p = strecpy(p,
176 "\n"
177 "\n"
178 "Command line options:\n"
179 " -v drv = Set video driver (see below)\n"
180 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
181 " -m drv = Set music driver (see below)\n"
182 " -b drv = Set the blitter to use (see below)\n"
183 " -r res = Set resolution (for instance 800x600)\n"
184 " -h = Display this help text\n"
185 " -t year = Set starting year\n"
186 " -d [[fac=]lvl[,...]]= Debug mode\n"
187 " -e = Start Editor\n"
188 " -g [savegame] = Start new/save game immediately\n"
189 " -G seed = Set random seed\n"
190 #if defined(ENABLE_NETWORK)
191 " -n [ip:port#company]= Join network game\n"
192 " -p password = Password to join server\n"
193 " -P password = Password to join company\n"
194 " -D [ip][:port] = Start dedicated server\n"
195 " -l ip[:port] = Redirect DEBUG()\n"
196 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
197 " -f = Fork into the background (dedicated only)\n"
198 #endif
199 #endif /* ENABLE_NETWORK */
200 " -I graphics_set = Force the graphics set (see below)\n"
201 " -S sounds_set = Force the sounds set (see below)\n"
202 " -M music_set = Force the music set (see below)\n"
203 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
204 " -x = Do not automatically save to config file on exit\n"
205 " -q savegame = Write some information about the savegame and exit\n"
206 "\n",
207 lastof(buf)
210 /* List the graphics packs */
211 p = BaseGraphics::GetSetsList(p, lastof(buf));
213 /* List the sounds packs */
214 p = BaseSounds::GetSetsList(p, lastof(buf));
216 /* List the music packs */
217 p = BaseMusic::GetSetsList(p, lastof(buf));
219 /* List the drivers */
220 p = DriverFactoryBase::GetDriversInfo(p, lastof(buf));
222 /* List the blitters */
223 p = BlitterFactory::GetBlittersInfo(p, lastof(buf));
225 /* List the debug facilities. */
226 p = DumpDebugFacilityNames(p, lastof(buf));
228 /* We need to initialize the AI, so it finds the AIs */
229 AI::Initialize();
230 p = AI::GetConsoleList(p, lastof(buf), true);
231 AI::Uninitialize(true);
233 /* We need to initialize the GameScript, so it finds the GSs */
234 Game::Initialize();
235 p = Game::GetConsoleList(p, lastof(buf), true);
236 Game::Uninitialize(true);
238 /* ShowInfo put output to stderr, but version information should go
239 * to stdout; this is the only exception */
240 #if !defined(WIN32) && !defined(WIN64)
241 printf("%s\n", buf);
242 #else
243 ShowInfo(buf);
244 #endif
247 static void WriteSavegameInfo(const char *name)
249 extern uint16 _sl_version;
250 uint32 last_ottd_rev = 0;
251 byte ever_modified = 0;
252 bool removed_newgrfs = false;
254 GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
256 char buf[8192];
257 char *p = buf;
258 p += seprintf(p, lastof(buf), "Name: %s\n", name);
259 p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
260 p += seprintf(p, lastof(buf), "NewGRF ver: 0x%08X\n", last_ottd_rev);
261 p += seprintf(p, lastof(buf), "Modified: %d\n", ever_modified);
263 if (removed_newgrfs) {
264 p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
267 p = strecpy(p, "NewGRFs:\n", lastof(buf));
268 if (_load_check_data.HasNewGrfs()) {
269 for (GRFConfig *c = _load_check_data.grfconfig; c != nullptr; c = c->next) {
270 char md5sum[33];
271 md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
272 p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
276 /* ShowInfo put output to stderr, but version information should go
277 * to stdout; this is the only exception */
278 #if !defined(WIN32) && !defined(WIN64)
279 printf("%s\n", buf);
280 #else
281 ShowInfo(buf);
282 #endif
287 * Extract the resolution from the given string and store
288 * it in the 'res' parameter.
289 * @param res variable to store the resolution in.
290 * @param s the string to decompose.
292 static void ParseResolution(Dimension *res, const char *s)
294 const char *t = strchr(s, 'x');
295 if (t == nullptr) {
296 ShowInfoF("Invalid resolution '%s'", s);
297 return;
300 res->width = max(strtoul(s, nullptr, 0), 64UL);
301 res->height = max(strtoul(t + 1, nullptr, 0), 64UL);
306 * Unitializes drivers, frees allocated memory, cleans pools, ...
307 * Generally, prepares the game for shutting down
309 static void ShutdownGame()
311 IConsoleFree();
313 if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
315 DriverFactoryBase::ShutdownDrivers();
317 UnInitWindowSystem();
319 /* stop the scripts */
320 AI::Uninitialize(false);
321 Game::Uninitialize(false);
323 /* Uninitialize variables that are allocated dynamically */
324 GamelogReset();
326 #ifdef ENABLE_NETWORK
327 free(_config_file);
328 #endif
330 LinkGraphSchedule::Clear();
331 ClearBridgeSimulatedSignalMapping();
332 ClearTraceRestrictMapping();
333 PoolBase::Clean(PT_ALL);
335 ClearZoningCaches();
337 /* No NewGRFs were loaded when it was still bootstrapping. */
338 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
340 /* Close all and any open filehandles */
341 FioCloseAll();
343 UninitFreeType();
345 ClearCommandLog();
347 ViewportMapClearTunnelCache();
351 * Load the introduction game.
352 * @param load_newgrfs Whether to load the NewGRFs or not.
354 static void LoadIntroGame(bool load_newgrfs = true)
356 _game_mode = GM_MENU;
358 if (load_newgrfs) ResetGRFConfig(false);
360 /* Setup main window */
361 ResetWindowSystem();
362 SetupColoursAndInitialWindow();
364 /* Load the default opening screen savegame */
365 if (SaveOrLoad("opntitle.dat", SLO_LOAD, DFT_GAME_FILE, BASESET_DIR) != SL_OK) {
366 GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
367 WaitTillGeneratedWorld();
368 SetLocalCompany(COMPANY_SPECTATOR);
369 } else {
370 SetLocalCompany(COMPANY_FIRST);
373 _pause_mode = PM_UNPAUSED;
374 _cursor.fix_at = false;
376 CheckForMissingGlyphs();
378 /* Play main theme */
379 if (MusicDriver::GetInstance()->IsSongPlaying()) ResetMusic();
382 void MakeNewgameSettingsLive()
384 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
385 if (_settings_game.ai_config[c] != nullptr) {
386 delete _settings_game.ai_config[c];
389 if (_settings_game.game_config != nullptr) {
390 delete _settings_game.game_config;
393 /* Copy newgame settings to active settings.
394 * Also initialise old settings needed for savegame conversion. */
395 _settings_game = _settings_newgame;
396 _old_vds = _settings_client.company.vehicle;
398 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
399 _settings_game.ai_config[c] = nullptr;
400 if (_settings_newgame.ai_config[c] != nullptr) {
401 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
404 _settings_game.game_config = nullptr;
405 if (_settings_newgame.game_config != nullptr) {
406 _settings_game.game_config = new GameConfig(_settings_newgame.game_config);
410 void OpenBrowser(const char *url)
412 /* Make sure we only accept urls that are sure to open a browser. */
413 if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
415 extern void OSOpenBrowser(const char *url);
416 OSOpenBrowser(url);
419 /** Callback structure of statements to be executed after the NewGRF scan. */
420 struct AfterNewGRFScan : NewGRFScanCallback {
421 Year startyear; ///< The start year.
422 uint generation_seed; ///< Seed for the new game.
423 char *dedicated_host; ///< Hostname for the dedicated server.
424 uint16 dedicated_port; ///< Port for the dedicated server.
425 char *network_conn; ///< Information about the server to connect to, or nullptr.
426 const char *join_server_password; ///< The password to join the server with.
427 const char *join_company_password; ///< The password to join the company with.
428 bool *save_config_ptr; ///< The pointer to the save config setting.
429 bool save_config; ///< The save config setting.
432 * Create a new callback.
433 * @param save_config_ptr Pointer to the save_config local variable which
434 * decides whether to save of exit or not.
436 AfterNewGRFScan(bool *save_config_ptr) :
437 startyear(INVALID_YEAR), generation_seed(GENERATE_NEW_SEED),
438 dedicated_host(nullptr), dedicated_port(0), network_conn(nullptr),
439 join_server_password(nullptr), join_company_password(nullptr),
440 save_config_ptr(save_config_ptr), save_config(true)
444 virtual void OnNewGRFsScanned()
446 ResetGRFConfig(false);
448 TarScanner::DoScan(TarScanner::SCENARIO);
450 AI::Initialize();
451 Game::Initialize();
453 /* We want the new (correct) NewGRF count to survive the loading. */
454 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
455 LoadFromConfig();
456 _settings_client.gui.last_newgrf_count = last_newgrf_count;
457 /* Since the default for the palette might have changed due to
458 * reading the configuration file, recalculate that now. */
459 UpdateNewGRFConfigPalette();
461 Game::Uninitialize(true);
462 AI::Uninitialize(true);
463 CheckConfig();
464 LoadFromHighScore();
465 LoadHotkeysFromConfig();
466 WindowDesc::LoadFromConfig();
468 /* We have loaded the config, so we may possibly save it. */
469 *save_config_ptr = save_config;
471 /* restore saved music volume */
472 MusicDriver::GetInstance()->SetVolume(_settings_client.music.music_vol);
474 if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
475 if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
477 #if defined(ENABLE_NETWORK)
478 if (dedicated_host != nullptr) {
479 _network_bind_list.Clear();
480 *_network_bind_list.Append() = stredup(dedicated_host);
482 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
483 #endif /* ENABLE_NETWORK */
485 /* initialize the ingame console */
486 IConsoleInit();
487 InitializeGUI();
488 IConsoleCmdExec("exec scripts/autoexec.scr 0");
490 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
491 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
493 #ifdef ENABLE_NETWORK
494 if (_network_available && network_conn != nullptr) {
495 const char *port = nullptr;
496 const char *company = nullptr;
497 uint16 rport = NETWORK_DEFAULT_PORT;
498 CompanyID join_as = COMPANY_NEW_COMPANY;
500 ParseConnectionString(&company, &port, network_conn);
502 if (company != nullptr) {
503 join_as = (CompanyID)atoi(company);
505 if (join_as != COMPANY_SPECTATOR) {
506 join_as--;
507 if (join_as >= MAX_COMPANIES) {
508 delete this;
509 return;
513 if (port != nullptr) rport = atoi(port);
515 LoadIntroGame();
516 _switch_mode = SM_NONE;
517 NetworkClientConnectGame(NetworkAddress(network_conn, rport), join_as, join_server_password, join_company_password);
519 #endif /* ENABLE_NETWORK */
521 /* After the scan we're not used anymore. */
522 delete this;
526 #if defined(UNIX) && !defined(__MORPHOS__)
527 extern void DedicatedFork();
528 #endif
530 /** Options of OpenTTD. */
531 static const OptionData _options[] = {
532 GETOPT_SHORT_VALUE('I'),
533 GETOPT_SHORT_VALUE('S'),
534 GETOPT_SHORT_VALUE('M'),
535 GETOPT_SHORT_VALUE('m'),
536 GETOPT_SHORT_VALUE('s'),
537 GETOPT_SHORT_VALUE('v'),
538 GETOPT_SHORT_VALUE('b'),
539 #if defined(ENABLE_NETWORK)
540 GETOPT_SHORT_OPTVAL('D'),
541 GETOPT_SHORT_OPTVAL('n'),
542 GETOPT_SHORT_VALUE('l'),
543 GETOPT_SHORT_VALUE('p'),
544 GETOPT_SHORT_VALUE('P'),
545 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
546 GETOPT_SHORT_NOVAL('f'),
547 #endif
548 #endif /* ENABLE_NETWORK */
549 GETOPT_SHORT_VALUE('r'),
550 GETOPT_SHORT_VALUE('t'),
551 GETOPT_SHORT_OPTVAL('d'),
552 GETOPT_SHORT_NOVAL('e'),
553 GETOPT_SHORT_OPTVAL('g'),
554 GETOPT_SHORT_VALUE('G'),
555 GETOPT_SHORT_VALUE('c'),
556 GETOPT_SHORT_NOVAL('x'),
557 GETOPT_SHORT_VALUE('q'),
558 GETOPT_SHORT_NOVAL('h'),
559 GETOPT_END()
563 * Main entry point for this lovely game.
564 * @param argc The number of arguments passed to this game.
565 * @param argv The values of the arguments.
566 * @return 0 when there is no error.
568 int openttd_main(int argc, char *argv[])
570 char *musicdriver = nullptr;
571 char *sounddriver = nullptr;
572 char *videodriver = nullptr;
573 char *blitter = nullptr;
574 char *graphics_set = nullptr;
575 char *sounds_set = nullptr;
576 char *music_set = nullptr;
577 Dimension resolution = {0, 0};
578 /* AfterNewGRFScan sets save_config to true after scanning completed. */
579 bool save_config = false;
580 AfterNewGRFScan *scanner = new AfterNewGRFScan(&save_config);
581 #if defined(ENABLE_NETWORK)
582 bool dedicated = false;
583 char *debuglog_conn = nullptr;
585 extern bool _dedicated_forks;
586 _dedicated_forks = false;
587 #endif /* ENABLE_NETWORK */
589 _game_mode = GM_MENU;
590 _switch_mode = SM_MENU;
591 _config_file = nullptr;
593 GetOptData mgo(argc - 1, argv + 1, _options);
594 int ret = 0;
596 int i;
597 while ((i = mgo.GetOpt()) != -1) {
598 switch (i) {
599 case 'I': free(graphics_set); graphics_set = stredup(mgo.opt); break;
600 case 'S': free(sounds_set); sounds_set = stredup(mgo.opt); break;
601 case 'M': free(music_set); music_set = stredup(mgo.opt); break;
602 case 'm': free(musicdriver); musicdriver = stredup(mgo.opt); break;
603 case 's': free(sounddriver); sounddriver = stredup(mgo.opt); break;
604 case 'v': free(videodriver); videodriver = stredup(mgo.opt); break;
605 case 'b': free(blitter); blitter = stredup(mgo.opt); break;
606 #if defined(ENABLE_NETWORK)
607 case 'D':
608 free(musicdriver);
609 free(sounddriver);
610 free(videodriver);
611 free(blitter);
612 musicdriver = stredup("null");
613 sounddriver = stredup("null");
614 videodriver = stredup("dedicated");
615 blitter = stredup("null");
616 dedicated = true;
617 SetDebugString("net=6");
618 if (mgo.opt != nullptr) {
619 /* Use the existing method for parsing (openttd -n).
620 * However, we do ignore the #company part. */
621 const char *temp = nullptr;
622 const char *port = nullptr;
623 ParseConnectionString(&temp, &port, mgo.opt);
624 if (!StrEmpty(mgo.opt)) scanner->dedicated_host = mgo.opt;
625 if (port != nullptr) scanner->dedicated_port = atoi(port);
627 break;
628 case 'f': _dedicated_forks = true; break;
629 case 'n':
630 scanner->network_conn = mgo.opt; // optional IP parameter, nullptr if unset
631 break;
632 case 'l':
633 debuglog_conn = mgo.opt;
634 break;
635 case 'p':
636 scanner->join_server_password = mgo.opt;
637 break;
638 case 'P':
639 scanner->join_company_password = mgo.opt;
640 break;
641 #endif /* ENABLE_NETWORK */
642 case 'r': ParseResolution(&resolution, mgo.opt); break;
643 case 't': scanner->startyear = atoi(mgo.opt); break;
644 case 'd': {
645 #if defined(WIN32)
646 CreateConsole();
647 #endif
648 if (mgo.opt != nullptr) SetDebugString(mgo.opt);
649 break;
651 case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
652 case 'g':
653 if (mgo.opt != nullptr) {
654 _file_to_saveload.SetName(mgo.opt);
655 bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
656 _switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
657 _file_to_saveload.SetMode(SLO_LOAD, is_scenario ? FT_SCENARIO : FT_SAVEGAME, DFT_GAME_FILE);
659 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
660 const char *t = strrchr(_file_to_saveload.name, '.');
661 if (t != nullptr) {
662 FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, t, nullptr, nullptr);
663 if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
666 break;
669 _switch_mode = SM_NEWGAME;
670 /* Give a random map if no seed has been given */
671 if (scanner->generation_seed == GENERATE_NEW_SEED) {
672 scanner->generation_seed = InteractiveRandom();
674 break;
675 case 'q': {
676 DeterminePaths(argv[0]);
677 if (StrEmpty(mgo.opt)) {
678 ret = 1;
679 goto exit_noshutdown;
682 char title[80];
683 title[0] = '\0';
684 FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
686 _load_check_data.Clear();
687 SaveOrLoadResult res = SaveOrLoad(mgo.opt, SLO_CHECK, DFT_GAME_FILE, SAVE_DIR, false);
688 if (res != SL_OK || _load_check_data.HasErrors()) {
689 fprintf(stderr, "Failed to open savegame\n");
690 if (_load_check_data.HasErrors()) {
691 char buf[256];
692 SetDParamStr(0, _load_check_data.error_data);
693 GetString(buf, _load_check_data.error, lastof(buf));
694 fprintf(stderr, "%s\n", buf);
696 goto exit_noshutdown;
699 WriteSavegameInfo(title);
701 goto exit_noshutdown;
703 case 'G': scanner->generation_seed = atoi(mgo.opt); break;
704 case 'c': free(_config_file); _config_file = stredup(mgo.opt); break;
705 case 'x': scanner->save_config = false; break;
706 case 'h':
707 i = -2; // Force printing of help.
708 break;
710 if (i == -2) break;
713 if (i == -2 || mgo.numleft > 0) {
714 /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
715 * In all cases, print the help, and exit.
717 * The next two functions are needed to list the graphics sets. We can't do them earlier
718 * because then we cannot show it on the debug console as that hasn't been configured yet. */
719 DeterminePaths(argv[0]);
720 TarScanner::DoScan(TarScanner::BASESET);
721 BaseGraphics::FindSets();
722 BaseSounds::FindSets();
723 BaseMusic::FindSets();
724 ShowHelp();
726 goto exit_noshutdown;
729 #if defined(WINCE) && defined(_DEBUG)
730 /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
731 SetDebugString("4");
732 #endif
734 DeterminePaths(argv[0]);
735 TarScanner::DoScan(TarScanner::BASESET);
737 #if defined(ENABLE_NETWORK)
738 if (dedicated) DEBUG(net, 0, "Starting dedicated version %s", _openttd_revision);
739 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
741 #if defined(UNIX) && !defined(__MORPHOS__)
742 /* We must fork here, or we'll end up without some resources we need (like sockets) */
743 if (_dedicated_forks) DedicatedFork();
744 #endif
745 #endif
747 LoadFromConfig(true);
749 if (resolution.width != 0) _cur_resolution = resolution;
752 * The width and height must be at least 1 pixel and width times
753 * height times bytes per pixel must still fit within a 32 bits
754 * integer, even for 32 bpp video modes. This way all internal
755 * drawing routines work correctly.
757 _cur_resolution.width = ClampU(_cur_resolution.width, 1, UINT16_MAX / 2);
758 _cur_resolution.height = ClampU(_cur_resolution.height, 1, UINT16_MAX / 2);
760 /* Assume the cursor starts within the game as not all video drivers
761 * get an event that the cursor is within the window when it is opened.
762 * Saying the cursor is there makes no visible difference as it would
763 * just be out of the bounds of the window. */
764 _cursor.in_window = true;
766 /* enumerate language files */
767 InitializeLanguagePacks();
769 /* Initialize the regular font for FreeType */
770 InitFreeType(false);
772 /* This must be done early, since functions use the SetWindowDirty* calls */
773 InitWindowSystem();
775 BaseGraphics::FindSets();
776 if (graphics_set == nullptr && BaseGraphics::ini_set != nullptr) graphics_set = stredup(BaseGraphics::ini_set);
777 if (!BaseGraphics::SetSet(graphics_set)) {
778 if (!StrEmpty(graphics_set)) {
779 BaseGraphics::SetSet(nullptr);
781 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
782 msg.SetDParamStr(0, graphics_set);
783 ScheduleErrorMessage(msg);
786 free(graphics_set);
788 /* Initialize game palette */
789 GfxInitPalettes();
791 DEBUG(misc, 1, "Loading blitter...");
792 if (blitter == nullptr && _ini_blitter != nullptr) blitter = stredup(_ini_blitter);
793 _blitter_autodetected = StrEmpty(blitter);
794 /* Activate the initial blitter.
795 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
796 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
797 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
798 * - Use 8bpp blitter otherwise.
800 if (!_blitter_autodetected ||
801 (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
802 BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
803 if (BlitterFactory::SelectBlitter(blitter) == nullptr) {
804 StrEmpty(blitter) ?
805 usererror("Failed to autoprobe blitter") :
806 usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
809 free(blitter);
811 if (videodriver == nullptr && _ini_videodriver != nullptr) videodriver = stredup(_ini_videodriver);
812 DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
813 free(videodriver);
815 InitializeSpriteSorter();
817 /* Initialize the zoom level of the screen to normal */
818 _screen.zoom = ZOOM_LVL_NORMAL;
820 NetworkStartUp(); // initialize network-core
822 #if defined(ENABLE_NETWORK)
823 if (debuglog_conn != nullptr && _network_available) {
824 const char *not_used = nullptr;
825 const char *port = nullptr;
826 uint16 rport;
828 rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
830 ParseConnectionString(&not_used, &port, debuglog_conn);
831 if (port != nullptr) rport = atoi(port);
833 NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
835 #endif /* ENABLE_NETWORK */
837 if (!HandleBootstrap()) {
838 ShutdownGame();
840 goto exit_bootstrap;
843 VideoDriver::GetInstance()->ClaimMousePointer();
845 /* initialize screenshot formats */
846 InitializeScreenshotFormats();
848 BaseSounds::FindSets();
849 if (sounds_set == nullptr && BaseSounds::ini_set != nullptr) sounds_set = stredup(BaseSounds::ini_set);
850 if (!BaseSounds::SetSet(sounds_set)) {
851 if (StrEmpty(sounds_set) || !BaseSounds::SetSet(nullptr)) {
852 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
853 } else {
854 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
855 msg.SetDParamStr(0, sounds_set);
856 ScheduleErrorMessage(msg);
859 free(sounds_set);
861 BaseMusic::FindSets();
862 if (music_set == nullptr && BaseMusic::ini_set != nullptr) music_set = stredup(BaseMusic::ini_set);
863 if (!BaseMusic::SetSet(music_set)) {
864 if (StrEmpty(music_set) || !BaseMusic::SetSet(nullptr)) {
865 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
866 } else {
867 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
868 msg.SetDParamStr(0, music_set);
869 ScheduleErrorMessage(msg);
872 free(music_set);
874 if (sounddriver == nullptr && _ini_sounddriver != nullptr) sounddriver = stredup(_ini_sounddriver);
875 DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
876 free(sounddriver);
878 if (musicdriver == nullptr && _ini_musicdriver != nullptr) musicdriver = stredup(_ini_musicdriver);
879 DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
880 free(musicdriver);
882 /* Take our initial lock on whatever we might want to do! */
883 _modal_progress_paint_mutex->BeginCritical();
884 _modal_progress_work_mutex->BeginCritical();
886 GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
887 WaitTillGeneratedWorld();
889 LoadIntroGame(false);
891 CheckForMissingGlyphs();
893 /* ScanNewGRFFiles now has control over the scanner. */
894 ScanNewGRFFiles(scanner);
895 scanner = nullptr;
897 VideoDriver::GetInstance()->MainLoop();
899 WaitTillSaved();
901 /* only save config if we have to */
902 if (save_config) {
903 SaveToConfig();
904 SaveHotkeysToConfig();
905 WindowDesc::SaveToConfig();
906 SaveToHighScore();
909 /* Reset windowing system, stop drivers, free used memory, ... */
910 ShutdownGame();
911 goto exit_normal;
913 exit_noshutdown:
914 /* These three are normally freed before bootstrap. */
915 free(graphics_set);
916 free(videodriver);
917 free(blitter);
919 exit_bootstrap:
920 /* These are normally freed before exit, but after bootstrap. */
921 free(sounds_set);
922 free(music_set);
923 free(musicdriver);
924 free(sounddriver);
926 exit_normal:
927 free(BaseGraphics::ini_set);
928 free(BaseSounds::ini_set);
929 free(BaseMusic::ini_set);
931 free(_ini_musicdriver);
932 free(_ini_sounddriver);
933 free(_ini_videodriver);
934 free(_ini_blitter);
936 delete scanner;
938 #ifdef ENABLE_NETWORK
939 extern FILE *_log_fd;
940 if (_log_fd != nullptr) {
941 fclose(_log_fd);
943 #endif /* ENABLE_NETWORK */
945 return ret;
948 void HandleExitGameRequest()
950 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
951 _exit_game = true;
952 } else if (_settings_client.gui.autosave_on_exit) {
953 DoExitSave();
954 _exit_game = true;
955 } else {
956 AskExitGame();
960 static void MakeNewGameDone()
962 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
964 extern void PostCheckNewGRFLoadWarnings();
965 PostCheckNewGRFLoadWarnings();
967 /* In a dedicated server, the server does not play */
968 if (!VideoDriver::GetInstance()->HasGUI()) {
969 SetLocalCompany(COMPANY_SPECTATOR);
970 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
971 IConsoleCmdExec("exec scripts/game_start.scr 0");
972 return;
975 /* Create a single company */
976 DoStartupNewCompany(false);
978 Company *c = Company::Get(COMPANY_FIRST);
979 c->settings = _settings_client.company;
981 IConsoleCmdExec("exec scripts/game_start.scr 0");
983 SetLocalCompany(COMPANY_FIRST);
985 InitializeRailGUI();
986 InitializeRoadGUI();
988 #ifdef ENABLE_NETWORK
989 /* We are the server, we start a new company (not dedicated),
990 * so set the default password *if* needed. */
991 if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
992 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
994 #endif /* ENABLE_NETWORK */
996 if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
998 CheckEngines();
999 CheckIndustries();
1000 MarkWholeScreenDirty();
1003 static void MakeNewGame(bool from_heightmap, bool reset_settings)
1005 _game_mode = GM_NORMAL;
1007 ResetGRFConfig(true);
1009 GenerateWorldSetCallback(&MakeNewGameDone);
1010 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
1013 static void MakeNewEditorWorldDone()
1015 SetLocalCompany(OWNER_NONE);
1017 extern void PostCheckNewGRFLoadWarnings();
1018 PostCheckNewGRFLoadWarnings();
1021 static void MakeNewEditorWorld()
1023 _game_mode = GM_EDITOR;
1025 ResetGRFConfig(true);
1027 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
1028 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1032 * Load the specified savegame but on error do different things.
1033 * If loading fails due to corrupt savegame, bad version, etc. go back to
1034 * a previous correct state. In the menu for example load the intro game again.
1035 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
1036 * @param newgm switch to this mode of loading fails due to some unknown error
1037 * @param filename file to be loaded
1038 * @param subdir default directory to look for filename, set to 0 if not needed
1039 * @param lf Load filter to use, if nullptr: use filename + subdir.
1041 bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr)
1043 assert(fop == SLO_LOAD);
1044 assert(dft == DFT_GAME_FILE || (lf == nullptr && dft == DFT_OLD_GAME_FILE));
1045 GameMode ogm = _game_mode;
1047 _game_mode = newgm;
1049 switch (lf == nullptr ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
1050 case SL_OK: return true;
1052 case SL_REINIT:
1053 #ifdef ENABLE_NETWORK
1054 if (_network_dedicated) {
1056 * We need to reinit a network map...
1057 * We can't simply load the intro game here as that game has many
1058 * special cases which make clients desync immediately. So we fall
1059 * back to just generating a new game with the current settings.
1061 DEBUG(net, 0, "Loading game failed, so a new (random) game will be started!");
1062 MakeNewGame(false, true);
1063 return false;
1065 if (_network_server) {
1066 /* We can't load the intro game as server, so disconnect first. */
1067 NetworkDisconnect();
1069 #endif /* ENABLE_NETWORK */
1071 switch (ogm) {
1072 default:
1073 case GM_MENU: LoadIntroGame(); break;
1074 case GM_EDITOR: MakeNewEditorWorld(); break;
1076 return false;
1078 default:
1079 _game_mode = ogm;
1080 return false;
1084 void SwitchToMode(SwitchMode new_mode)
1086 #ifdef ENABLE_NETWORK
1087 /* If we are saving something, the network stays in his current state */
1088 if (new_mode != SM_SAVE_GAME) {
1089 /* If the network is active, make it not-active */
1090 if (_networking) {
1091 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1092 NetworkReboot();
1093 } else {
1094 NetworkDisconnect();
1098 /* If we are a server, we restart the server */
1099 if (_is_network_server) {
1100 /* But not if we are going to the menu */
1101 if (new_mode != SM_MENU) {
1102 /* check if we should reload the config */
1103 if (_settings_client.network.reload_cfg) {
1104 LoadFromConfig();
1105 MakeNewgameSettingsLive();
1106 ResetGRFConfig(false);
1108 NetworkServerStart();
1109 } else {
1110 /* This client no longer wants to be a network-server */
1111 _is_network_server = false;
1115 #endif /* ENABLE_NETWORK */
1116 /* Make sure all AI controllers are gone at quitting game */
1117 if (new_mode != SM_SAVE_GAME) AI::KillAll();
1119 switch (new_mode) {
1120 case SM_EDITOR: // Switch to scenario editor
1121 MakeNewEditorWorld();
1122 break;
1124 case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1125 case SM_NEWGAME: // New Game --> 'Random game'
1126 #ifdef ENABLE_NETWORK
1127 if (_network_server) {
1128 seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "Random Map");
1130 #endif /* ENABLE_NETWORK */
1131 MakeNewGame(false, new_mode == SM_NEWGAME);
1132 break;
1134 case SM_LOAD_GAME: { // Load game, Play Scenario
1135 ResetGRFConfig(true);
1136 ResetWindowSystem();
1138 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, NO_DIRECTORY)) {
1139 SetDParamStr(0, GetSaveLoadErrorString());
1140 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1141 } else {
1142 if (_file_to_saveload.abstract_ftype == FT_SCENARIO) {
1143 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1144 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1146 /* Update the local company for a loaded game. It is either always
1147 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1148 SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
1150 if (_ctrl_pressed && !_network_dedicated) {
1151 DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
1154 /* Execute the game-start script */
1155 IConsoleCmdExec("exec scripts/game_start.scr 0");
1156 /* Decrease pause counter (was increased from opening load dialog) */
1157 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1158 #ifdef ENABLE_NETWORK
1159 if (_network_server) {
1160 seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
1162 #endif /* ENABLE_NETWORK */
1164 break;
1167 case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1168 #ifdef ENABLE_NETWORK
1169 if (_network_server) {
1170 seprintf(_network_game_info.map_name, lastof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
1172 #endif /* ENABLE_NETWORK */
1173 MakeNewGame(true, true);
1174 break;
1176 case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1177 SetLocalCompany(OWNER_NONE);
1179 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1180 MarkWholeScreenDirty();
1181 break;
1183 case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1184 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) {
1185 SetLocalCompany(OWNER_NONE);
1186 _settings_newgame.game_creation.starting_year = _cur_year;
1187 /* Cancel the saveload pausing */
1188 DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1189 } else {
1190 SetDParamStr(0, GetSaveLoadErrorString());
1191 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1193 break;
1196 case SM_MENU: // Switch to game intro menu
1197 LoadIntroGame();
1198 if (BaseSounds::ini_set == nullptr && BaseSounds::GetUsedSet()->fallback) {
1199 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1200 BaseSounds::ini_set = stredup(BaseSounds::GetUsedSet()->name);
1202 break;
1204 case SM_SAVE_GAME: // Save game.
1205 /* Make network saved games on pause compatible to singleplayer */
1206 if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
1207 SetDParamStr(0, GetSaveLoadErrorString());
1208 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1209 } else {
1210 DeleteWindowById(WC_SAVELOAD, 0);
1212 break;
1214 case SM_SAVE_HEIGHTMAP: // Save heightmap.
1215 MakeHeightmapScreenshot(_file_to_saveload.name);
1216 DeleteWindowById(WC_SAVELOAD, 0);
1217 break;
1219 case SM_GENRANDLAND: // Generate random land within scenario editor
1220 SetLocalCompany(OWNER_NONE);
1221 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1222 /* XXX: set date */
1223 MarkWholeScreenDirty();
1224 break;
1226 default: NOT_REACHED();
1229 SmallMapWindow::RebuildColourIndexIfNecessary();
1234 * Check the validity of some of the caches.
1235 * Especially in the sense of desyncs between
1236 * the cached value and what the value would
1237 * be when calculated from the 'base' data.
1239 void CheckCaches(bool force_check)
1241 if (!force_check) {
1242 /* Return here so it is easy to add checks that are run
1243 * always to aid testing of caches. */
1244 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);
1278 char buffer[4096];
1279 old_infrastructure.Get(i)->Dump(buffer, lastof(buffer));
1280 DEBUG(desync, 0, "Previous:\n%s", buffer);
1281 c->infrastructure.Dump(buffer, lastof(buffer));
1282 DEBUG(desync, 0, "Recalculated:\n%s", buffer);
1284 i++;
1287 /* Strict checking of the road stop cache entries */
1288 const RoadStop *rs;
1289 FOR_ALL_ROADSTOPS(rs) {
1290 if (IsStandardRoadStopTile(rs->xy)) continue;
1292 assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
1293 rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
1294 rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
1297 Vehicle *v;
1298 FOR_ALL_VEHICLES(v) {
1299 extern void FillNewGRFVehicleCache(const Vehicle *v);
1300 if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1302 uint length = 0;
1303 for (const Vehicle *u = v; u != nullptr; u = u->Next()) length++;
1305 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1306 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1307 GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
1308 TrainCache *tra_cache = CallocT<TrainCache>(length);
1310 length = 0;
1311 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1312 FillNewGRFVehicleCache(u);
1313 grf_cache[length] = u->grf_cache;
1314 veh_cache[length] = u->vcache;
1315 switch (u->type) {
1316 case VEH_TRAIN:
1317 gro_cache[length] = Train::From(u)->gcache;
1318 tra_cache[length] = Train::From(u)->tcache;
1319 break;
1320 case VEH_ROAD:
1321 gro_cache[length] = RoadVehicle::From(u)->gcache;
1322 break;
1323 default:
1324 break;
1326 length++;
1329 switch (v->type) {
1330 case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
1331 case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
1332 case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
1333 case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
1334 default: break;
1337 length = 0;
1338 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1339 FillNewGRFVehicleCache(u);
1340 if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1341 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);
1343 if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1344 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);
1346 switch (u->type) {
1347 case VEH_TRAIN:
1348 if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1349 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);
1351 if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1352 DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
1354 break;
1355 case VEH_ROAD:
1356 if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1357 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);
1359 break;
1360 default:
1361 break;
1363 length++;
1366 free(grf_cache);
1367 free(veh_cache);
1368 free(gro_cache);
1369 free(tra_cache);
1372 /* Check whether the caches are still valid */
1373 FOR_ALL_VEHICLES(v) {
1374 byte buff[sizeof(VehicleCargoList)];
1375 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1376 v->cargo.InvalidateCache();
1377 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1380 Station *st;
1381 FOR_ALL_STATIONS(st) {
1382 for (CargoID c = 0; c < NUM_CARGO; c++) {
1383 byte buff[sizeof(StationCargoList)];
1384 memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
1385 st->goods[c].cargo.InvalidateCache();
1386 assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
1392 * Network-safe forced desync check.
1393 * @param tile unused
1394 * @param flags operation to perform
1395 * @param p1 unused
1396 * @param p2 unused
1397 * @param text unused
1398 * @return the cost of this operation or an error
1400 CommandCost CmdDesyncCheck(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
1402 if (flags & DC_EXEC) {
1403 CheckCaches(true);
1406 return CommandCost();
1410 * State controlling game loop.
1411 * The state must not be changed from anywhere but here.
1412 * That check is enforced in DoCommand.
1414 void StateGameLoop()
1416 if (!_networking || _network_server) {
1417 extern void StateGameLoop_LinkGraphPauseControl();
1418 StateGameLoop_LinkGraphPauseControl();
1421 /* don't execute the state loop during pause */
1422 if (_pause_mode != PM_UNPAUSED) {
1423 UpdateLandscapingLimits();
1424 #ifndef DEBUG_DUMP_COMMANDS
1425 Game::GameLoop();
1426 #endif
1427 CallWindowTickEvent();
1428 return;
1430 if (HasModalProgress()) return;
1432 Layouter::ReduceLineCache();
1434 if (_game_mode == GM_EDITOR) {
1435 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1436 RunTileLoop();
1437 CallVehicleTicks();
1438 CallLandscapeTick();
1439 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1440 UpdateLandscapingLimits();
1442 CallWindowTickEvent();
1443 NewsLoop();
1444 } else {
1445 if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
1446 /* Save the desync savegame if needed. */
1447 char name[MAX_PATH];
1448 seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
1449 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
1452 CheckCaches(false);
1454 /* All these actions has to be done from OWNER_NONE
1455 * for multiplayer compatibility */
1456 Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1458 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1459 AnimateAnimatedTiles();
1460 IncreaseDate();
1461 RunTileLoop();
1462 CallVehicleTicks();
1463 CallLandscapeTick();
1464 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1466 #ifndef DEBUG_DUMP_COMMANDS
1467 AI::GameLoop();
1468 Game::GameLoop();
1469 #endif
1470 UpdateLandscapingLimits();
1472 CallWindowTickEvent();
1473 NewsLoop();
1474 cur_company.Restore();
1477 assert(IsLocalCompany());
1481 * Create an autosave. The default name is "autosave#.sav". However with
1482 * the setting 'keep_all_autosave' the name defaults to company-name + date
1484 static void DoAutosave()
1486 char buf[MAX_PATH];
1488 #if defined(PSP)
1489 /* Autosaving in networking is too time expensive for the PSP */
1490 if (_networking) return;
1491 #endif /* PSP */
1493 if (_settings_client.gui.keep_all_autosave) {
1494 GenerateDefaultSaveName(buf, lastof(buf));
1495 strecat(buf, ".sav", lastof(buf));
1496 } else {
1497 static int _autosave_ctr = 0;
1499 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1500 seprintf(buf, lastof(buf), "autosave%d.sav", _autosave_ctr);
1502 if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
1505 DEBUG(sl, 2, "Autosaving to '%s'", buf);
1506 if (SaveOrLoad(buf, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR) != SL_OK) {
1507 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED, INVALID_STRING_ID, WL_ERROR);
1511 void GameLoop()
1513 if (_game_mode == GM_BOOTSTRAP) {
1514 #ifdef ENABLE_NETWORK
1515 /* Check for UDP stuff */
1516 if (_network_available) NetworkBackgroundLoop();
1517 #endif
1518 InputLoop();
1519 return;
1522 ProcessAsyncSaveFinish();
1524 /* autosave game? */
1525 if (_do_autosave) {
1526 DoAutosave();
1527 _do_autosave = false;
1528 SetWindowDirty(WC_STATUS_BAR, 0);
1531 /* switch game mode? */
1532 if (_switch_mode != SM_NONE && !HasModalProgress()) {
1533 SwitchToMode(_switch_mode);
1534 _switch_mode = SM_NONE;
1537 IncreaseSpriteLRU();
1538 InteractiveRandom();
1540 extern int _caret_timer;
1541 _caret_timer += 3;
1542 CursorTick();
1544 #ifdef ENABLE_NETWORK
1545 /* Check for UDP stuff */
1546 if (_network_available) NetworkBackgroundLoop();
1548 if (_networking && !HasModalProgress()) {
1549 /* Multiplayer */
1550 NetworkGameLoop();
1551 } else {
1552 if (_network_reconnect > 0 && --_network_reconnect == 0) {
1553 /* This means that we want to reconnect to the last host
1554 * We do this here, because it means that the network is really closed */
1555 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), COMPANY_SPECTATOR);
1557 /* Singleplayer */
1558 StateGameLoop();
1561 /* Check chat messages roughly once a second. */
1562 static uint check_message = 0;
1563 if (++check_message > 1000 / MILLISECONDS_PER_TICK) {
1564 check_message = 0;
1565 NetworkChatMessageLoop();
1567 #else
1568 StateGameLoop();
1569 #endif /* ENABLE_NETWORK */
1571 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1573 if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects();
1575 InputLoop();
1577 SoundDriver::GetInstance()->MainLoop();
1578 MusicLoop();