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