OpenTTD Source: src/openttd.cpp Source File

OpenTTD Source 14.0-beta3

openttd.cpp
Go to the documentation of this file.
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
7
10 #include "stdafx.h"
11
12 #include "blitter/factory.hpp"
13 #include "sound/sound_driver.hpp"
14 #include "music/music_driver.hpp"
15 #include "video/video_driver.hpp"
16 #include "mixer.h"
17
18 #include "fontcache.h"
19 #include "error.h"
20 #include "error_func.h"
21 #include "gui.h"
22
23 #include "base_media_base.h"
24 #include "saveload/saveload.h"
25 #include "company_cmd.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_server.h"
38 #include "network/network_func.h"
39 #include "ai/ai.hpp"
40 #include "ai/ai_config.hpp"
41 #include "settings_func.h"
42 #include "genworld.h"
43 #include "progress.h"
44 #include "strings_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 "road_gui.h"
58 #include "core/backup_type.hpp"
59 #include "hotkeys.h"
60 #include "newgrf.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_func.h"
68 #include "viewport_sprite_sorter.h"
69 #include "framerate_type.h"
70 #include "industry.h"
71 #include "network/network_gui.h"
72 #include "network/network_survey.h"
73 #include "misc_cmd.h"
74 #include "timer/timer.h"
75 #include "timer/timer_game_calendar.h"
76 #include "timer/timer_game_economy.h"
77 #include "timer/timer_game_realtime.h"
78 #include "timer/timer_game_tick.h"
79 #include "social_integration.h"
80
81 #include "linkgraph/linkgraphschedule.h"
82
83 #include <system_error>
84
85 #include "safeguards.h"
86
87 #ifdef __EMSCRIPTEN__
88 # include <emscripten.h>
89 # include <emscripten/html5.h>
90 #endif
91
92 void CallLandscapeTick();
93 void DoPaletteAnimations();
94 void MusicLoop();
95 void CallWindowGameTickEvent();
96 bool HandleBootstrap();
97
98 extern void AfterLoadCompanyStats();
99 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
100 extern void OSOpenBrowser(const std::string &url);
101 extern void RebuildTownCaches();
102 extern void ShowOSErrorBox(const char *buf, bool system);
103 extern std::string _config_file;
104
105 bool _save_config = false;
106 bool _request_newgrf_scan = false;
107 NewGRFScanCallback *_request_newgrf_scan_callback = nullptr;
108
114 void UserErrorI(const std::string &str)
115 {
116 ShowOSErrorBox(str.c_str(), false);
117 if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
118
119 #ifdef __EMSCRIPTEN__
120 emscripten_exit_pointerlock();
121 /* In effect, the game ends here. As emscripten_set_main_loop() caused
122 * the stack to be unwound, the code after MainLoop() in
123 * openttd_main() is never executed. */
124 EM_ASM(if (window["openttd_abort"]) openttd_abort());
125 #endif
126
127 _exit(1);
128 }
129
135 void FatalErrorI(const std::string &str)
136 {
137 if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
138 ShowOSErrorBox(str.c_str(), true);
139 }
140
141 /* Set the error message for the crash log and then invoke it. */
142 CrashLog::SetErrorMessage(str);
143 abort();
144 }
145
149 static void ShowHelp()
150 {
151 std::string str;
152 str.reserve(8192);
153
154 std::back_insert_iterator<std::string> output_iterator = std::back_inserter(str);
155 fmt::format_to(output_iterator, "OpenTTD {}\n", _openttd_revision);
156 str +=
157 "\n"
158 "\n"
159 "Command line options:\n"
160 " -v drv = Set video driver (see below)\n"
161 " -s drv = Set sound driver (see below)\n"
162 " -m drv = Set music driver (see below)\n"
163 " -b drv = Set the blitter to use (see below)\n"
164 " -r res = Set resolution (for instance 800x600)\n"
165 " -h = Display this help text\n"
166 " -t year = Set starting year\n"
167 " -d [[fac=]lvl[,...]]= Debug mode\n"
168 " -e = Start Editor\n"
169 " -g [savegame|scenario|heightmap] = Start new/savegame/scenario/heightmap immediately\n"
170 " -G seed = Set random seed\n"
171 " -n host[:port][#company]= Join network game\n"
172 " -p password = Password to join server\n"
173 " -P password = Password to join company\n"
174 " -D [host][:port] = Start dedicated server\n"
175 #if !defined(_WIN32)
176 " -f = Fork into the background (dedicated only)\n"
177 #endif
178 " -I graphics_set = Force the graphics set (see below)\n"
179 " -S sounds_set = Force the sounds set (see below)\n"
180 " -M music_set = Force the music set (see below)\n"
181 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
182 " -x = Never save configuration changes to disk\n"
183 " -X = Don't use global folders to search for files\n"
184 " -q savegame = Write some information about the savegame and exit\n"
185 " -Q = Don't scan for/load NewGRF files on startup\n"
186 " -QQ = Disable NewGRF scanning/loading entirely\n"
187 "\n";
188
189 /* List the graphics packs */
190 BaseGraphics::GetSetsList(output_iterator);
191
192 /* List the sounds packs */
193 BaseSounds::GetSetsList(output_iterator);
194
195 /* List the music packs */
196 BaseMusic::GetSetsList(output_iterator);
197
198 /* List the drivers */
199 DriverFactoryBase::GetDriversInfo(output_iterator);
200
201 /* List the blitters */
202 BlitterFactory::GetBlittersInfo(output_iterator);
203
204 /* List the debug facilities. */
205 DumpDebugFacilityNames(output_iterator);
206
207 /* We need to initialize the AI, so it finds the AIs */
208 AI::Initialize();
209 AI::GetConsoleList(output_iterator, true);
210 AI::Uninitialize(true);
211
212 /* We need to initialize the GameScript, so it finds the GSs */
213 Game::Initialize();
214 Game::GetConsoleList(output_iterator, true);
215 Game::Uninitialize(true);
216
217 /* ShowInfo put output to stderr, but version information should go
218 * to stdout; this is the only exception */
219 #if !defined(_WIN32)
220 fmt::print("{}\n", str);
221 #else
222 ShowInfoI(str);
223 #endif
224 }
225
226 static void WriteSavegameInfo(const std::string &name)
227 {
228 extern SaveLoadVersion _sl_version;
229 uint32_t last_ottd_rev = 0;
230 byte ever_modified = 0;
231 bool removed_newgrfs = false;
232
233 _gamelog.Info(&last_ottd_rev, &ever_modified, &removed_newgrfs);
234
235 std::string message;
236 message.reserve(1024);
237 fmt::format_to(std::back_inserter(message), "Name: {}\n", name);
238 fmt::format_to(std::back_inserter(message), "Savegame ver: {}\n", _sl_version);
239 fmt::format_to(std::back_inserter(message), "NewGRF ver: 0x{:08X}\n", last_ottd_rev);
240 fmt::format_to(std::back_inserter(message), "Modified: {}\n", ever_modified);
241
242 if (removed_newgrfs) {
243 fmt::format_to(std::back_inserter(message), "NewGRFs have been removed\n");
244 }
245
246 message += "NewGRFs:\n";
247 if (_load_check_data.HasNewGrfs()) {
248 for (GRFConfig *c = _load_check_data.grfconfig; c != nullptr; c = c->next) {
249 fmt::format_to(std::back_inserter(message), "{:08X} {} {}\n", c->ident.grfid,
250 FormatArrayAsHex(HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum), c->filename);
251 }
252 }
253
254 /* ShowInfo put output to stderr, but version information should go
255 * to stdout; this is the only exception */
256 #if !defined(_WIN32)
257 fmt::print("{}\n", message);
258 #else
259 ShowInfoI(message);
260 #endif
261 }
262
263
270 static void ParseResolution(Dimension *res, const char *s)
271 {
272 const char *t = strchr(s, 'x');
273 if (t == nullptr) {
274 ShowInfo("Invalid resolution '{}'", s);
275 return;
276 }
277
278 res->width = std::max(std::strtoul(s, nullptr, 0), 64UL);
279 res->height = std::max(std::strtoul(t + 1, nullptr, 0), 64UL);
280 }
281
282
287 static void ShutdownGame()
288 {
289 IConsoleFree();
290
291 if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
292
293 SocialIntegration::Shutdown();
294 DriverFactoryBase::ShutdownDrivers();
295
296 UnInitWindowSystem();
297
298 /* stop the scripts */
299 AI::Uninitialize(false);
300 Game::Uninitialize(false);
301
302 /* Uninitialize variables that are allocated dynamically */
303 _gamelog.Reset();
304
305 LinkGraphSchedule::Clear();
306 PoolBase::Clean(PT_ALL);
307
308 /* No NewGRFs were loaded when it was still bootstrapping. */
309 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
310
311 UninitFontCache();
312 }
313
318 static void LoadIntroGame(bool load_newgrfs = true)
319 {
320 _game_mode = GM_MENU;
321
322 if (load_newgrfs) ResetGRFConfig(false);
323
324 /* Setup main window */
325 ResetWindowSystem();
326 SetupColoursAndInitialWindow();
327
328 /* Load the default opening screen savegame */
329 if (SaveOrLoad("opntitle.dat", SLO_LOAD, DFT_GAME_FILE, BASESET_DIR) != SL_OK) {
330 GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
331 SetLocalCompany(COMPANY_SPECTATOR);
332 } else {
333 SetLocalCompany(COMPANY_FIRST);
334 }
335
336 FixTitleGameZoom();
337 _pause_mode = PM_UNPAUSED;
338 _cursor.fix_at = false;
339
340 CheckForMissingGlyphs();
341
342 MusicLoop(); // ensure music is correct
343 }
344
345 void MakeNewgameSettingsLive()
346 {
347 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
348 if (_settings_game.ai_config[c] != nullptr) {
349 delete _settings_game.ai_config[c];
350 }
351 }
352 if (_settings_game.game_config != nullptr) {
353 delete _settings_game.game_config;
354 }
355
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
361 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
362 _settings_game.ai_config[c] = nullptr;
363 if (_settings_newgame.ai_config[c] != nullptr) {
364 _settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
365 }
366 }
367 _settings_game.game_config = nullptr;
368 if (_settings_newgame.game_config != nullptr) {
369 _settings_game.game_config = new GameConfig(_settings_newgame.game_config);
370 }
371 }
372
373 void OpenBrowser(const std::string &url)
374 {
375 /* Make sure we only accept urls that are sure to open a browser. */
376 if (url.starts_with("http://") || url.starts_with("https://")) {
377 OSOpenBrowser(url);
378 }
379 }
380
382 struct AfterNewGRFScan : NewGRFScanCallback {
383 TimerGameCalendar::Year startyear = CalendarTime::INVALID_YEAR;
384 uint32_t generation_seed = GENERATE_NEW_SEED;
385 std::string dedicated_host;
386 uint16_t dedicated_port = 0;
387 std::string connection_string;
388 std::string join_server_password;
389 std::string join_company_password;
390 bool save_config = true;
391
395 AfterNewGRFScan()
396 {
397 /* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
398 * if it's placed outside a member function, directly in the struct body. */
399 static_assert(sizeof(generation_seed) == sizeof(_settings_game.game_creation.generation_seed));
400 }
401
402 void OnNewGRFsScanned() override
403 {
404 ResetGRFConfig(false);
405
406 TarScanner::DoScan(TarScanner::SCENARIO);
407
408 AI::Initialize();
409 Game::Initialize();
410
411 /* We want the new (correct) NewGRF count to survive the loading. */
412 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
413 LoadFromConfig();
414 _settings_client.gui.last_newgrf_count = last_newgrf_count;
415 /* Since the default for the palette might have changed due to
416 * reading the configuration file, recalculate that now. */
417 UpdateNewGRFConfigPalette();
418
419 Game::Uninitialize(true);
420 AI::Uninitialize(true);
421 LoadFromHighScore();
422 LoadHotkeysFromConfig();
423 WindowDesc::LoadFromConfig();
424
425 /* We have loaded the config, so we may possibly save it. */
426 _save_config = save_config;
427
428 /* restore saved music and effects volumes */
429 MusicDriver::GetInstance()->SetVolume(_settings_client.music.music_vol);
430 SetEffectVolume(_settings_client.music.effect_vol);
431
432 if (startyear != CalendarTime::INVALID_YEAR) IConsoleSetSetting("game_creation.starting_year", startyear.base());
433 _settings_newgame.game_creation.generation_seed = generation_seed;
434
435 if (!dedicated_host.empty()) {
436 _network_bind_list.clear();
437 _network_bind_list.emplace_back(dedicated_host);
438 }
439 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
440
441 /* initialize the ingame console */
442 IConsoleInit();
443 InitializeGUI();
444 IConsoleCmdExec("exec scripts/autoexec.scr 0");
445
446 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
447 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
448
449 if (_network_available && !connection_string.empty()) {
450 LoadIntroGame();
451 _switch_mode = SM_NONE;
452
453 NetworkClientConnectGame(connection_string, COMPANY_NEW_COMPANY, join_server_password, join_company_password);
454 }
455
456 /* After the scan we're not used anymore. */
457 delete this;
458 }
459 };
460
461 void PostMainLoop()
462 {
463 WaitTillSaved();
464
465 /* only save config if we have to */
466 if (_save_config) {
467 SaveToConfig();
468 SaveHotkeysToConfig();
469 WindowDesc::SaveToConfig();
470 SaveToHighScore();
471 }
472
473 /* Reset windowing system, stop drivers, free used memory, ... */
474 ShutdownGame();
475 }
476
477 #if defined(UNIX)
478 extern void DedicatedFork();
479 #endif
480
482 static const OptionData _options[] = {
483 GETOPT_SHORT_VALUE('I'),
484 GETOPT_SHORT_VALUE('S'),
485 GETOPT_SHORT_VALUE('M'),
486 GETOPT_SHORT_VALUE('m'),
487 GETOPT_SHORT_VALUE('s'),
488 GETOPT_SHORT_VALUE('v'),
489 GETOPT_SHORT_VALUE('b'),
490 GETOPT_SHORT_OPTVAL('D'),
491 GETOPT_SHORT_VALUE('n'),
492 GETOPT_SHORT_VALUE('p'),
493 GETOPT_SHORT_VALUE('P'),
494 #if !defined(_WIN32)
495 GETOPT_SHORT_NOVAL('f'),
496 #endif
497 GETOPT_SHORT_VALUE('r'),
498 GETOPT_SHORT_VALUE('t'),
499 GETOPT_SHORT_OPTVAL('d'),
500 GETOPT_SHORT_NOVAL('e'),
501 GETOPT_SHORT_OPTVAL('g'),
502 GETOPT_SHORT_VALUE('G'),
503 GETOPT_SHORT_VALUE('c'),
504 GETOPT_SHORT_NOVAL('x'),
505 GETOPT_SHORT_NOVAL('X'),
506 GETOPT_SHORT_VALUE('q'),
507 GETOPT_SHORT_NOVAL('h'),
508 GETOPT_SHORT_NOVAL('Q'),
509 GETOPT_END()
510 };
511
518 int openttd_main(int argc, char *argv[])
519 {
520 std::string musicdriver;
521 std::string sounddriver;
522 std::string videodriver;
523 std::string blitter;
524 std::string graphics_set;
525 std::string sounds_set;
526 std::string music_set;
527 Dimension resolution = {0, 0};
528 std::unique_ptr<AfterNewGRFScan> scanner(new AfterNewGRFScan());
529 bool dedicated = false;
530 bool only_local_path = false;
531
532 extern bool _dedicated_forks;
533 _dedicated_forks = false;
534
535 _game_mode = GM_MENU;
536 _switch_mode = SM_MENU;
537
538 GetOptData mgo(argc - 1, argv + 1, _options);
539 int ret = 0;
540
541 int i;
542 while ((i = mgo.GetOpt()) != -1) {
543 switch (i) {
544 case 'I': graphics_set = mgo.opt; break;
545 case 'S': sounds_set = mgo.opt; break;
546 case 'M': music_set = mgo.opt; break;
547 case 'm': musicdriver = mgo.opt; break;
548 case 's': sounddriver = mgo.opt; break;
549 case 'v': videodriver = mgo.opt; break;
550 case 'b': blitter = mgo.opt; break;
551 case 'D':
552 musicdriver = "null";
553 sounddriver = "null";
554 videodriver = "dedicated";
555 blitter = "null";
556 dedicated = true;
557 SetDebugString("net=4", ShowInfoI);
558 if (mgo.opt != nullptr) {
559 scanner->dedicated_host = ParseFullConnectionString(mgo.opt, scanner->dedicated_port);
560 }
561 break;
562 case 'f': _dedicated_forks = true; break;
563 case 'n':
564 scanner->connection_string = mgo.opt; // host:port#company parameter
565 break;
566 case 'p':
567 scanner->join_server_password = mgo.opt;
568 break;
569 case 'P':
570 scanner->join_company_password = mgo.opt;
571 break;
572 case 'r': ParseResolution(&resolution, mgo.opt); break;
573 case 't': scanner->startyear = atoi(mgo.opt); break;
574 case 'd': {
575 #if defined(_WIN32)
576 CreateConsole();
577 #endif
578 if (mgo.opt != nullptr) SetDebugString(mgo.opt, ShowInfoI);
579 break;
580 }
581 case 'e':
582 /* Allow for '-e' before or after '-g'. */
583 switch (_switch_mode) {
584 case SM_MENU: _switch_mode = SM_EDITOR; break;
585 case SM_LOAD_GAME: _switch_mode = SM_LOAD_SCENARIO; break;
586 case SM_START_HEIGHTMAP: _switch_mode = SM_LOAD_HEIGHTMAP; break;
587 default: break;
588 }
589 break;
590 case 'g':
591 if (mgo.opt != nullptr) {
592 _file_to_saveload.name = mgo.opt;
593
594 std::string extension = std::filesystem::path(_file_to_saveload.name).extension().string();
595 auto [ft, _] = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, extension);
596 if (ft == FIOS_TYPE_INVALID) {
597 std::tie(ft, _) = FiosGetScenarioListCallback(SLO_LOAD, _file_to_saveload.name, extension);
598 }
599 if (ft == FIOS_TYPE_INVALID) {
600 std::tie(ft, _) = FiosGetHeightmapListCallback(SLO_LOAD, _file_to_saveload.name, extension);
601 }
602
603 /* Allow for '-e' before or after '-g'. */
604 switch (GetAbstractFileType(ft)) {
605 case FT_SAVEGAME: _switch_mode = (_switch_mode == SM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME); break;
606 case FT_SCENARIO: _switch_mode = (_switch_mode == SM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME); break;
607 case FT_HEIGHTMAP: _switch_mode = (_switch_mode == SM_EDITOR ? SM_LOAD_HEIGHTMAP : SM_START_HEIGHTMAP); break;
608 default: break;
609 }
610
611 _file_to_saveload.SetMode(SLO_LOAD, GetAbstractFileType(ft), GetDetailedFileType(ft));
612 break;
613 }
614
615 _switch_mode = SM_NEWGAME;
616 /* Give a random map if no seed has been given */
617 if (scanner->generation_seed == GENERATE_NEW_SEED) {
618 scanner->generation_seed = InteractiveRandom();
619 }
620 break;
621 case 'q': {
622 DeterminePaths(argv[0], only_local_path);
623 if (StrEmpty(mgo.opt)) {
624 ret = 1;
625 return ret;
626 }
627
628 auto [_, title] = FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, strrchr(mgo.opt, '.'));
629
630 _load_check_data.Clear();
631 SaveOrLoadResult res = SaveOrLoad(mgo.opt, SLO_CHECK, DFT_GAME_FILE, SAVE_DIR, false);
632 if (res != SL_OK || _load_check_data.HasErrors()) {
633 fmt::print(stderr, "Failed to open savegame\n");
634 if (_load_check_data.HasErrors()) {
635 InitializeLanguagePacks(); // A language pack is needed for GetString()
636 SetDParamStr(0, _load_check_data.error_msg);
637 fmt::print(stderr, "{}\n", GetString(_load_check_data.error));
638 }
639 return ret;
640 }
641
642 WriteSavegameInfo(title);
643 return ret;
644 }
645 case 'Q': {
646 extern int _skip_all_newgrf_scanning;
647 _skip_all_newgrf_scanning += 1;
648 break;
649 }
650 case 'G': scanner->generation_seed = std::strtoul(mgo.opt, nullptr, 10); break;
651 case 'c': _config_file = mgo.opt; break;
652 case 'x': scanner->save_config = false; break;
653 case 'X': only_local_path = true; break;
654 case 'h':
655 i = -2; // Force printing of help.
656 break;
657 }
658 if (i == -2) break;
659 }
660
661 if (i == -2 || mgo.numleft > 0) {
662 /* Either the user typed '-h', they made an error, or they added unrecognized command line arguments.
663 * In all cases, print the help, and exit.
664 *
665 * The next two functions are needed to list the graphics sets. We can't do them earlier
666 * because then we cannot show it on the debug console as that hasn't been configured yet. */
667 DeterminePaths(argv[0], only_local_path);
668 TarScanner::DoScan(TarScanner::BASESET);
669 BaseGraphics::FindSets();
670 BaseSounds::FindSets();
671 BaseMusic::FindSets();
672 ShowHelp();
673 return ret;
674 }
675
676 DeterminePaths(argv[0], only_local_path);
677 TarScanner::DoScan(TarScanner::BASESET);
678
679 if (dedicated) Debug(net, 3, "Starting dedicated server, version {}", _openttd_revision);
680 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
681
682 #if defined(UNIX)
683 /* We must fork here, or we'll end up without some resources we need (like sockets) */
684 if (_dedicated_forks) DedicatedFork();
685 #endif
686
687 LoadFromConfig(true);
688
689 if (resolution.width != 0) _cur_resolution = resolution;
690
691 /* Limit width times height times bytes per pixel to fit a 32 bit
692 * integer, This way all internal drawing routines work correctly.
693 * A resolution that has one component as 0 is treated as a marker to
694 * auto-detect a good window size. */
695 _cur_resolution.width = std::min(_cur_resolution.width, UINT16_MAX / 2u);
696 _cur_resolution.height = std::min(_cur_resolution.height, UINT16_MAX / 2u);
697
698 /* Assume the cursor starts within the game as not all video drivers
699 * get an event that the cursor is within the window when it is opened.
700 * Saying the cursor is there makes no visible difference as it would
701 * just be out of the bounds of the window. */
702 _cursor.in_window = true;
703
704 /* enumerate language files */
705 InitializeLanguagePacks();
706
707 /* Initialize the font cache */
708 InitFontCache(false);
709
710 /* This must be done early, since functions use the SetWindowDirty* calls */
711 InitWindowSystem();
712
713 BaseGraphics::FindSets();
714 bool valid_graphics_set;
715 if (!graphics_set.empty()) {
716 valid_graphics_set = BaseGraphics::SetSetByName(graphics_set);
717 } else if (BaseGraphics::ini_data.shortname != 0) {
718 graphics_set = BaseGraphics::ini_data.name;
719 valid_graphics_set = BaseGraphics::SetSetByShortname(BaseGraphics::ini_data.shortname);
720 if (valid_graphics_set && !BaseGraphics::ini_data.extra_params.empty()) {
721 GRFConfig &extra_cfg = BaseGraphics::GetUsedSet()->GetOrCreateExtraConfig();
722 if (extra_cfg.IsCompatible(BaseGraphics::ini_data.extra_version)) {
723 extra_cfg.SetParams(BaseGraphics::ini_data.extra_params);
724 }
725 }
726 } else if (!BaseGraphics::ini_data.name.empty()) {
727 graphics_set = BaseGraphics::ini_data.name;
728 valid_graphics_set = BaseGraphics::SetSetByName(BaseGraphics::ini_data.name);
729 } else {
730 valid_graphics_set = true;
731 BaseGraphics::SetSet(nullptr); // ignore error, continue to bootstrap GUI
732 }
733 if (!valid_graphics_set) {
734 BaseGraphics::SetSet(nullptr);
735
736 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
737 msg.SetDParamStr(0, graphics_set);
738 ScheduleErrorMessage(msg);
739 }
740
741 /* Initialize game palette */
742 GfxInitPalettes();
743
744 Debug(misc, 1, "Loading blitter...");
745 if (blitter.empty() && !_ini_blitter.empty()) blitter = _ini_blitter;
746 _blitter_autodetected = blitter.empty();
747 /* Activate the initial blitter.
748 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
749 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
750 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
751 * - Use 8bpp blitter otherwise.
752 */
753 if (!_blitter_autodetected ||
754 (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
755 BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
756 if (BlitterFactory::SelectBlitter(blitter) == nullptr) {
757 blitter.empty() ?
758 UserError("Failed to autoprobe blitter") :
759 UserError("Failed to select requested blitter '{}'; does it exist?", blitter);
760 }
761 }
762
763 if (videodriver.empty() && !_ini_videodriver.empty()) videodriver = _ini_videodriver;
764 DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
765
766 InitializeSpriteSorter();
767
768 /* Initialize the zoom level of the screen to normal */
769 _screen.zoom = ZOOM_LVL_NORMAL;
770
771 /* The video driver is now selected, now initialise GUI zoom */
772 AdjustGUIZoom(false);
773
774 SocialIntegration::Initialize();
775 NetworkStartUp(); // initialize network-core
776
777 if (!HandleBootstrap()) {
778 ShutdownGame();
779 return ret;
780 }
781
782 VideoDriver::GetInstance()->ClaimMousePointer();
783
784 /* initialize screenshot formats */
785 InitializeScreenshotFormats();
786
787 BaseSounds::FindSets();
788 if (sounds_set.empty() && !BaseSounds::ini_set.empty()) sounds_set = BaseSounds::ini_set;
789 if (!BaseSounds::SetSetByName(sounds_set)) {
790 if (sounds_set.empty() || !BaseSounds::SetSet({})) {
791 UserError("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
792 } else {
793 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
794 msg.SetDParamStr(0, sounds_set);
795 ScheduleErrorMessage(msg);
796 }
797 }
798
799 BaseMusic::FindSets();
800 if (music_set.empty() && !BaseMusic::ini_set.empty()) music_set = BaseMusic::ini_set;
801 if (!BaseMusic::SetSetByName(music_set)) {
802 if (music_set.empty() || !BaseMusic::SetSet({})) {
803 UserError("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
804 } else {
805 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
806 msg.SetDParamStr(0, music_set);
807 ScheduleErrorMessage(msg);
808 }
809 }
810
811 if (sounddriver.empty() && !_ini_sounddriver.empty()) sounddriver = _ini_sounddriver;
812 DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
813
814 if (musicdriver.empty() && !_ini_musicdriver.empty()) musicdriver = _ini_musicdriver;
815 DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
816
817 GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
818 LoadIntroGame(false);
819
820 CheckForMissingGlyphs();
821
822 /* ScanNewGRFFiles now has control over the scanner. */
823 RequestNewGRFScan(scanner.release());
824
825 VideoDriver::GetInstance()->MainLoop();
826
827 PostMainLoop();
828 return ret;
829 }
830
831 void HandleExitGameRequest()
832 {
833 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
834 _exit_game = true;
835 } else if (_settings_client.gui.autosave_on_exit) {
836 DoExitSave();
837 _survey.Transmit(NetworkSurveyHandler::Reason::EXIT, true);
838 _exit_game = true;
839 } else {
840 AskExitGame();
841 }
842 }
843
847 static void OnStartScenario()
848 {
849 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
850 EngineOverrideManager::ResetToCurrentNewGRFConfig();
851
852 /* Make sure all industries were built "this year", to avoid too early closures. (#9918) */
853 for (Industry *i : Industry::Iterate()) {
854 i->last_prod_year = TimerGameEconomy::year;
855 }
856 }
857
862 static void OnStartGame(bool dedicated_server)
863 {
864 /* Update the local company for a loaded game. It is either the first available company
865 * or in the case of a dedicated server, a spectator */
866 SetLocalCompany(dedicated_server ? COMPANY_SPECTATOR : GetFirstPlayableCompanyID());
867
868 /* Update the static game info to set the values from the new game. */
869 NetworkServerUpdateGameInfo();
870 /* Execute the game-start script */
871 IConsoleCmdExec("exec scripts/game_start.scr 0");
872 }
873
874 static void MakeNewGameDone()
875 {
876 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
877
878 /* In a dedicated server, the server does not play */
879 if (!VideoDriver::GetInstance()->HasGUI()) {
880 OnStartGame(true);
881 if (_settings_client.gui.pause_on_newgame) Command<CMD_PAUSE>::Post(PM_PAUSED_NORMAL, true);
882 return;
883 }
884
885 /* Create a single company */
886 DoStartupNewCompany(false);
887
888 Company *c = Company::Get(COMPANY_FIRST);
889 c->settings = _settings_client.company;
890
891 /* Overwrite color from settings if needed
892 * COLOUR_END corresponds to Random colour */
893
894 if (_settings_client.gui.starting_colour != COLOUR_END) {
895 c->colour = _settings_client.gui.starting_colour;
896 ResetCompanyLivery(c);
897 _company_colours[c->index] = c->colour;
898 }
899
900 if (_settings_client.gui.starting_colour_secondary != COLOUR_END && HasBit(_loaded_newgrf_features.used_liveries, LS_DEFAULT)) {
901 Command<CMD_SET_COMPANY_COLOUR>::Post(LS_DEFAULT, false, _settings_client.gui.starting_colour_secondary);
902 }
903
904 OnStartGame(false);
905
906 InitializeRailGUI();
907 InitializeRoadGUI();
908
909 /* We are the server, we start a new company (not dedicated),
910 * so set the default password *if* needed. */
911 if (_network_server && !_settings_client.network.default_company_pass.empty()) {
912 NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
913 }
914
915 if (_settings_client.gui.pause_on_newgame) Command<CMD_PAUSE>::Post(PM_PAUSED_NORMAL, true);
916
917 CheckEngines();
918 CheckIndustries();
919 MarkWholeScreenDirty();
920
921 if (_network_server) {
922 ChangeNetworkRestartTime(true);
923
924 if (!_network_dedicated) ShowClientList();
925 }
926 }
927
928 static void MakeNewGame(bool from_heightmap, bool reset_settings)
929 {
930 _game_mode = GM_NORMAL;
931 if (!from_heightmap) {
932 /* "reload" command needs to know what mode we were in. */
933 _file_to_saveload.SetMode(SLO_INVALID, FT_INVALID, DFT_INVALID);
934 }
935
936 ResetGRFConfig(true);
937
938 GenerateWorldSetCallback(&MakeNewGameDone);
939 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
940 }
941
942 static void MakeNewEditorWorldDone()
943 {
944 SetLocalCompany(OWNER_NONE);
945 }
946
947 static void MakeNewEditorWorld()
948 {
949 _game_mode = GM_EDITOR;
950 /* "reload" command needs to know what mode we were in. */
951 _file_to_saveload.SetMode(SLO_INVALID, FT_INVALID, DFT_INVALID);
952
953 ResetGRFConfig(true);
954
955 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
956 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
957 }
958
969 bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, std::shared_ptr<LoadFilter> lf = nullptr)
970 {
971 assert(fop == SLO_LOAD);
972 assert(dft == DFT_GAME_FILE || (lf == nullptr && dft == DFT_OLD_GAME_FILE));
973 GameMode ogm = _game_mode;
974
975 _game_mode = newgm;
976
977 SaveOrLoadResult result = (lf == nullptr) ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf);
978 if (result == SL_OK) return true;
979
980 if (_network_dedicated && ogm == GM_MENU) {
981 /*
982 * If we are a dedicated server *and* we just were in the menu, then we
983 * are loading the first savegame. If that fails, not starting the
984 * server is a better reaction than starting the server with a newly
985 * generated map as it is quite likely to be started from a script.
986 */
987 Debug(net, 0, "Loading requested map failed; closing server.");
988 _exit_game = true;
989 return false;
990 }
991
992 if (result != SL_REINIT) {
993 _game_mode = ogm;
994 return false;
995 }
996
997 if (_network_dedicated) {
998 /*
999 * If we are a dedicated server, have already loaded/started a game,
1000 * and then loading the savegame fails in a manner that we need to
1001 * reinitialize everything. We must not fall back into the menu mode
1002 * with the intro game, as that is unjoinable by clients. So there is
1003 * nothing else to do than start a new game, as it might have failed
1004 * trying to reload the originally loaded savegame/scenario.
1005 */
1006 Debug(net, 0, "Loading game failed, so a new (random) game will be started");
1007 MakeNewGame(false, true);
1008 return false;
1009 }
1010
1011 if (_network_server) {
1012 /* We can't load the intro game as server, so disconnect first. */
1013 NetworkDisconnect();
1014 }
1015
1016 switch (ogm) {
1017 default:
1018 case GM_MENU: LoadIntroGame(); break;
1019 case GM_EDITOR: MakeNewEditorWorld(); break;
1020 }
1021 return false;
1022 }
1023
1024 static void UpdateSocialIntegration(GameMode game_mode)
1025 {
1026 switch (game_mode) {
1027 case GM_BOOTSTRAP:
1028 case GM_MENU:
1029 SocialIntegration::EventEnterMainMenu();
1030 break;
1031
1032 case GM_NORMAL:
1033 if (_networking) {
1034 SocialIntegration::EventEnterMultiplayer(Map::SizeX(), Map::SizeY());
1035 } else {
1036 SocialIntegration::EventEnterSingleplayer(Map::SizeX(), Map::SizeY());
1037 }
1038 break;
1039
1040 case GM_EDITOR:
1041 SocialIntegration::EventEnterScenarioEditor(Map::SizeX(), Map::SizeY());
1042 break;
1043 }
1044 }
1045
1046 void SwitchToMode(SwitchMode new_mode)
1047 {
1048 /* If we are saving something, the network stays in its current state */
1049 if (new_mode != SM_SAVE_GAME) {
1050 /* If the network is active, make it not-active */
1051 if (_networking) {
1052 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1053 NetworkReboot();
1054 } else {
1055 NetworkDisconnect();
1056 }
1057 }
1058
1059 /* If we are a server, we restart the server */
1060 if (_is_network_server) {
1061 /* But not if we are going to the menu */
1062 if (new_mode != SM_MENU) {
1063 /* check if we should reload the config */
1064 if (_settings_client.network.reload_cfg) {
1065 LoadFromConfig();
1066 MakeNewgameSettingsLive();
1067 ResetGRFConfig(false);
1068 }
1069 NetworkServerStart();
1070 } else {
1071 /* This client no longer wants to be a network-server */
1072 _is_network_server = false;
1073 }
1074 }
1075 }
1076
1077 /* Make sure all AI controllers are gone at quitting game */
1078 if (new_mode != SM_SAVE_GAME) AI::KillAll();
1079
1080 /* When we change mode, reset the autosave. */
1081 if (new_mode != SM_SAVE_GAME) ChangeAutosaveFrequency(true);
1082
1083 /* Transmit the survey if we were in normal-mode and not saving. It always means we leaving the current game. */
1084 if (_game_mode == GM_NORMAL && new_mode != SM_SAVE_GAME) _survey.Transmit(NetworkSurveyHandler::Reason::LEAVE);
1085
1086 /* Keep track when we last switch mode. Used for survey, to know how long someone was in a game. */
1087 if (new_mode != SM_SAVE_GAME) _switch_mode_time = std::chrono::steady_clock::now();
1088
1089 switch (new_mode) {
1090 case SM_EDITOR: // Switch to scenario editor
1091 MakeNewEditorWorld();
1092 GenerateSavegameId();
1093
1094 UpdateSocialIntegration(GM_EDITOR);
1095 break;
1096
1097 case SM_RELOADGAME: // Reload with what-ever started the game
1098 if (_file_to_saveload.abstract_ftype == FT_SAVEGAME || _file_to_saveload.abstract_ftype == FT_SCENARIO) {
1099 /* Reload current savegame/scenario */
1100 _switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
1101 SwitchToMode(_switch_mode);
1102 break;
1103 } else if (_file_to_saveload.abstract_ftype == FT_HEIGHTMAP) {
1104 /* Restart current heightmap */
1105 _switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_HEIGHTMAP : SM_RESTART_HEIGHTMAP;
1106 SwitchToMode(_switch_mode);
1107 break;
1108 }
1109
1110 MakeNewGame(false, new_mode == SM_NEWGAME);
1111 GenerateSavegameId();
1112
1113 UpdateSocialIntegration(GM_NORMAL);
1114 break;
1115
1116 case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1117 case SM_NEWGAME: // New Game --> 'Random game'
1118 MakeNewGame(false, new_mode == SM_NEWGAME);
1119 GenerateSavegameId();
1120
1121 UpdateSocialIntegration(GM_NORMAL);
1122 break;
1123
1124 case SM_LOAD_GAME: { // Load game, Play Scenario
1125 ResetGRFConfig(true);
1126 ResetWindowSystem();
1127
1128 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, NO_DIRECTORY)) {
1129 SetDParamStr(0, GetSaveLoadErrorString());
1130 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_CRITICAL);
1131 } else {
1132 if (_file_to_saveload.abstract_ftype == FT_SCENARIO) {
1133 OnStartScenario();
1134 }
1135 OnStartGame(_network_dedicated);
1136 /* Decrease pause counter (was increased from opening load dialog) */
1137 Command<CMD_PAUSE>::Post(PM_PAUSED_SAVELOAD, false);
1138 }
1139
1140 UpdateSocialIntegration(GM_NORMAL);
1141 break;
1142 }
1143
1144 case SM_RESTART_HEIGHTMAP: // Load a heightmap and start a new game from it with current settings
1145 case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1146 MakeNewGame(true, new_mode == SM_START_HEIGHTMAP);
1147 GenerateSavegameId();
1148
1149 UpdateSocialIntegration(GM_NORMAL);
1150 break;
1151
1152 case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1153 SetLocalCompany(OWNER_NONE);
1154
1155 _game_mode = GM_EDITOR;
1156
1157 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1158 GenerateSavegameId();
1159 MarkWholeScreenDirty();
1160
1161 UpdateSocialIntegration(GM_EDITOR);
1162 break;
1163
1164 case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1165 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) {
1166 SetLocalCompany(OWNER_NONE);
1167 GenerateSavegameId();
1168 _settings_newgame.game_creation.starting_year = TimerGameCalendar::year;
1169 /* Cancel the saveload pausing */
1170 Command<CMD_PAUSE>::Post(PM_PAUSED_SAVELOAD, false);
1171 } else {
1172 SetDParamStr(0, GetSaveLoadErrorString());
1173 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_CRITICAL);
1174 }
1175
1176 UpdateSocialIntegration(GM_EDITOR);
1177 break;
1178 }
1179
1180 case SM_JOIN_GAME: // Join a multiplayer game
1181 LoadIntroGame();
1182 NetworkClientJoinGame();
1183
1184 SocialIntegration::EventJoiningMultiplayer();
1185 break;
1186
1187 case SM_MENU: // Switch to game intro menu
1188 LoadIntroGame();
1189 if (BaseSounds::ini_set.empty() && BaseSounds::GetUsedSet()->fallback && SoundDriver::GetInstance()->HasOutput()) {
1190 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1191 BaseSounds::ini_set = BaseSounds::GetUsedSet()->name;
1192 }
1193 if (_settings_client.network.participate_survey == PS_ASK) {
1194 /* No matter how often you go back to the main menu, only ask the first time. */
1195 static bool asked_once = false;
1196 if (!asked_once) {
1197 asked_once = true;
1198 ShowNetworkAskSurvey();
1199 }
1200 }
1201
1202 UpdateSocialIntegration(GM_MENU);
1203 break;
1204
1205 case SM_SAVE_GAME: // Save game.
1206 /* Make network saved games on pause compatible to singleplayer mode */
1207 if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
1208 SetDParamStr(0, GetSaveLoadErrorString());
1209 ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1210 } else {
1211 CloseWindowById(WC_SAVELOAD, 0);
1212 }
1213 break;
1214
1215 case SM_SAVE_HEIGHTMAP: // Save heightmap.
1216 MakeHeightmapScreenshot(_file_to_saveload.name.c_str());
1217 CloseWindowById(WC_SAVELOAD, 0);
1218 break;
1219
1220 case SM_GENRANDLAND: // Generate random land within scenario editor
1221 SetLocalCompany(OWNER_NONE);
1222 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1223 /* XXX: set date */
1224 MarkWholeScreenDirty();
1225 break;
1226
1227 default: NOT_REACHED();
1228 }
1229 }
1230
1231
1238 static void CheckCaches()
1239 {
1240 /* Return here so it is easy to add checks that are run
1241 * always to aid testing of caches. */
1242 if (_debug_desync_level <= 1) return;
1243
1244 /* Check the town caches. */
1245 std::vector<TownCache> old_town_caches;
1246 for (const Town *t : Town::Iterate()) {
1247 old_town_caches.push_back(t->cache);
1248 }
1249
1250 RebuildTownCaches();
1251 RebuildSubsidisedSourceAndDestinationCache();
1252
1253 uint i = 0;
1254 for (Town *t : Town::Iterate()) {
1255 if (MemCmpT(old_town_caches.data() + i, &t->cache) != 0) {
1256 Debug(desync, 2, "town cache mismatch: town {}", t->index);
1257 }
1258 i++;
1259 }
1260
1261 /* Check company infrastructure cache. */
1262 std::vector<CompanyInfrastructure> old_infrastructure;
1263 for (const Company *c : Company::Iterate()) old_infrastructure.push_back(c->infrastructure);
1264
1265 AfterLoadCompanyStats();
1266
1267 i = 0;
1268 for (const Company *c : Company::Iterate()) {
1269 if (MemCmpT(old_infrastructure.data() + i, &c->infrastructure) != 0) {
1270 Debug(desync, 2, "infrastructure cache mismatch: company {}", c->index);
1271 }
1272 i++;
1273 }
1274
1275 /* Strict checking of the road stop cache entries */
1276 for (const RoadStop *rs : RoadStop::Iterate()) {
1277 if (IsBayRoadStopTile(rs->xy)) continue;
1278
1279 assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
1280 rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
1281 rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
1282 }
1283
1284 for (Vehicle *v : Vehicle::Iterate()) {
1285 if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1286
1287 uint length = 0;
1288 for (const Vehicle *u = v; u != nullptr; u = u->Next()) length++;
1289
1290 NewGRFCache *grf_cache = CallocT<NewGRFCache>(length);
1291 VehicleCache *veh_cache = CallocT<VehicleCache>(length);
1292 GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
1293 TrainCache *tra_cache = CallocT<TrainCache>(length);
1294
1295 length = 0;
1296 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1297 FillNewGRFVehicleCache(u);
1298 grf_cache[length] = u->grf_cache;
1299 veh_cache[length] = u->vcache;
1300 switch (u->type) {
1301 case VEH_TRAIN:
1302 gro_cache[length] = Train::From(u)->gcache;
1303 tra_cache[length] = Train::From(u)->tcache;
1304 break;
1305 case VEH_ROAD:
1306 gro_cache[length] = RoadVehicle::From(u)->gcache;
1307 break;
1308 default:
1309 break;
1310 }
1311 length++;
1312 }
1313
1314 switch (v->type) {
1315 case VEH_TRAIN: Train::From(v)->ConsistChanged(CCF_TRACK); break;
1316 case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(v)); break;
1317 case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v)); break;
1318 case VEH_SHIP: Ship::From(v)->UpdateCache(); break;
1319 default: break;
1320 }
1321
1322 length = 0;
1323 for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1324 FillNewGRFVehicleCache(u);
1325 if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1326 Debug(desync, 2, "newgrf cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v->type, v->index, v->owner, v->unitnumber, length);
1327 }
1328 if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1329 Debug(desync, 2, "vehicle cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v->type, v->index, v->owner, v->unitnumber, length);
1330 }
1331 switch (u->type) {
1332 case VEH_TRAIN:
1333 if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1334 Debug(desync, 2, "train ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->index, v->owner, v->unitnumber, length);
1335 }
1336 if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1337 Debug(desync, 2, "train cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->index, v->owner, v->unitnumber, length);
1338 }
1339 break;
1340 case VEH_ROAD:
1341 if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1342 Debug(desync, 2, "road vehicle ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->index, v->owner, v->unitnumber, length);
1343 }
1344 break;
1345 default:
1346 break;
1347 }
1348 length++;
1349 }
1350
1351 free(grf_cache);
1352 free(veh_cache);
1353 free(gro_cache);
1354 free(tra_cache);
1355 }
1356
1357 /* Check whether the caches are still valid */
1358 for (Vehicle *v : Vehicle::Iterate()) {
1359 byte buff[sizeof(VehicleCargoList)];
1360 memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1361 v->cargo.InvalidateCache();
1362 assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1363 }
1364
1365 /* Backup stations_near */
1366 std::vector<StationList> old_town_stations_near;
1367 for (Town *t : Town::Iterate()) old_town_stations_near.push_back(t->stations_near);
1368
1369 std::vector<StationList> old_industry_stations_near;
1370 for (Industry *ind : Industry::Iterate()) old_industry_stations_near.push_back(ind->stations_near);
1371
1372 for (Station *st : Station::Iterate()) {
1373 for (GoodsEntry &ge : st->goods) {
1374 byte buff[sizeof(StationCargoList)];
1375 memcpy(buff, &ge.cargo, sizeof(StationCargoList));
1376 ge.cargo.InvalidateCache();
1377 assert(memcmp(&ge.cargo, buff, sizeof(StationCargoList)) == 0);
1378 }
1379
1380 /* Check docking tiles */
1381 TileArea ta;
1382 std::map<TileIndex, bool> docking_tiles;
1383 for (TileIndex tile : st->docking_station) {
1384 ta.Add(tile);
1385 docking_tiles[tile] = IsDockingTile(tile);
1386 }
1387 UpdateStationDockingTiles(st);
1388 if (ta.tile != st->docking_station.tile || ta.w != st->docking_station.w || ta.h != st->docking_station.h) {
1389 Debug(desync, 2, "station docking mismatch: station {}, company {}", st->index, st->owner);
1390 }
1391 for (TileIndex tile : ta) {
1392 if (docking_tiles[tile] != IsDockingTile(tile)) {
1393 Debug(desync, 2, "docking tile mismatch: tile {}", tile);
1394 }
1395 }
1396
1397 /* Check industries_near */
1398 IndustryList industries_near = st->industries_near;
1399 st->RecomputeCatchment();
1400 if (st->industries_near != industries_near) {
1401 Debug(desync, 2, "station industries near mismatch: station {}", st->index);
1402 }
1403 }
1404
1405 /* Check stations_near */
1406 i = 0;
1407 for (Town *t : Town::Iterate()) {
1408 if (t->stations_near != old_town_stations_near[i]) {
1409 Debug(desync, 2, "town stations near mismatch: town {}", t->index);
1410 }
1411 i++;
1412 }
1413 i = 0;
1414 for (Industry *ind : Industry::Iterate()) {
1415 if (ind->stations_near != old_industry_stations_near[i]) {
1416 Debug(desync, 2, "industry stations near mismatch: industry {}", ind->index);
1417 }
1418 i++;
1419 }
1420 }
1421
1427 void StateGameLoop()
1428 {
1429 if (!_networking || _network_server) {
1430 StateGameLoop_LinkGraphPauseControl();
1431 }
1432
1433 /* Don't execute the state loop during pause or when modal windows are open. */
1434 if (_pause_mode != PM_UNPAUSED || HasModalProgress()) {
1435 PerformanceMeasurer::Paused(PFE_GAMELOOP);
1436 PerformanceMeasurer::Paused(PFE_GL_ECONOMY);
1437 PerformanceMeasurer::Paused(PFE_GL_TRAINS);
1438 PerformanceMeasurer::Paused(PFE_GL_ROADVEHS);
1439 PerformanceMeasurer::Paused(PFE_GL_SHIPS);
1440 PerformanceMeasurer::Paused(PFE_GL_AIRCRAFT);
1441 PerformanceMeasurer::Paused(PFE_GL_LANDSCAPE);
1442
1443 if (!HasModalProgress()) UpdateLandscapingLimits();
1444 #ifndef DEBUG_DUMP_COMMANDS
1445 Game::GameLoop();
1446 #endif
1447 return;
1448 }
1449
1450 PerformanceMeasurer framerate(PFE_GAMELOOP);
1451 PerformanceAccumulator::Reset(PFE_GL_LANDSCAPE);
1452
1453 Layouter::ReduceLineCache();
1454
1455 if (_game_mode == GM_EDITOR) {
1456 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1457 RunTileLoop();
1458 CallVehicleTicks();
1459 CallLandscapeTick();
1460 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1461 UpdateLandscapingLimits();
1462
1463 CallWindowGameTickEvent();
1464 NewsLoop();
1465 } else {
1466 if (_debug_desync_level > 2 && TimerGameEconomy::date_fract == 0 && (TimerGameEconomy::date.base() & 0x1F) == 0) {
1467 /* Save the desync savegame if needed. */
1468 std::string name = fmt::format("dmp_cmds_{:08x}_{:08x}.sav", _settings_game.game_creation.generation_seed, TimerGameEconomy::date);
1469 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
1470 }
1471
1472 CheckCaches();
1473
1474 /* All these actions has to be done from OWNER_NONE
1475 * for multiplayer compatibility */
1476 Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1477
1478 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1479 AnimateAnimatedTiles();
1480 if (TimerManager<TimerGameCalendar>::Elapsed(1)) {
1481 RunVehicleCalendarDayProc();
1482 }
1483 TimerManager<TimerGameEconomy>::Elapsed(1);
1484 TimerManager<TimerGameTick>::Elapsed(1);
1485 RunTileLoop();
1486 CallVehicleTicks();
1487 CallLandscapeTick();
1488 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1489
1490 #ifndef DEBUG_DUMP_COMMANDS
1491 {
1492 PerformanceMeasurer script_framerate(PFE_ALLSCRIPTS);
1493 AI::GameLoop();
1494 Game::GameLoop();
1495 }
1496 #endif
1497 UpdateLandscapingLimits();
1498
1499 CallWindowGameTickEvent();
1500 NewsLoop();
1501 cur_company.Restore();
1502 }
1503
1504 assert(IsLocalCompany());
1505 }
1506
1508 static IntervalTimer<TimerGameRealtime> _autosave_interval({std::chrono::milliseconds::zero(), TimerGameRealtime::AUTOSAVE}, [](auto)
1509 {
1510 /* We reset the command-during-pause mode here, so we don't continue
1511 * to make auto-saves when nothing more is changing. */
1512 _pause_mode &= ~PM_COMMAND_DURING_PAUSE;
1513
1514 _do_autosave = true;
1515 SetWindowDirty(WC_STATUS_BAR, 0);
1516
1517 static FiosNumberedSaveName _autosave_ctr("autosave");
1518 DoAutoOrNetsave(_autosave_ctr);
1519
1520 _do_autosave = false;
1521 SetWindowDirty(WC_STATUS_BAR, 0);
1522 });
1523
1533 void ChangeAutosaveFrequency(bool reset)
1534 {
1535 _autosave_interval.SetInterval({std::chrono::minutes(_settings_client.gui.autosave_interval), TimerGameRealtime::AUTOSAVE}, reset);
1536 }
1537
1546 bool RequestNewGRFScan(NewGRFScanCallback *callback)
1547 {
1548 if (_request_newgrf_scan) return false;
1549
1550 _request_newgrf_scan = true;
1551 _request_newgrf_scan_callback = callback;
1552 return true;
1553 }
1554
1555 void GameLoop()
1556 {
1557 if (_game_mode == GM_BOOTSTRAP) {
1558 /* Check for UDP stuff */
1559 if (_network_available) NetworkBackgroundLoop();
1560 return;
1561 }
1562
1563 if (_request_newgrf_scan) {
1564 ScanNewGRFFiles(_request_newgrf_scan_callback);
1565 _request_newgrf_scan = false;
1566 _request_newgrf_scan_callback = nullptr;
1567 /* In case someone closed the game during our scan, don't do anything else. */
1568 if (_exit_game) return;
1569 }
1570
1571 ProcessAsyncSaveFinish();
1572
1573 if (_game_mode == GM_NORMAL) {
1574 static auto last_time = std::chrono::steady_clock::now();
1575 auto now = std::chrono::steady_clock::now();
1576 auto delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_time);
1577 if (delta_ms.count() != 0) {
1578 TimerManager<TimerGameRealtime>::Elapsed(delta_ms);
1579 last_time = now;
1580 }
1581 }
1582
1583 /* switch game mode? */
1584 if (_switch_mode != SM_NONE && !HasModalProgress()) {
1585 SwitchToMode(_switch_mode);
1586 _switch_mode = SM_NONE;
1587 if (_exit_game) return;
1588 }
1589
1590 IncreaseSpriteLRU();
1591
1592 /* Check for UDP stuff */
1593 if (_network_available) NetworkBackgroundLoop();
1594
1595 DebugSendRemoteMessages();
1596
1597 if (_networking && !HasModalProgress()) {
1598 /* Multiplayer */
1599 NetworkGameLoop();
1600 } else {
1601 if (_network_reconnect > 0 && --_network_reconnect == 0) {
1602 /* This means that we want to reconnect to the last host
1603 * We do this here, because it means that the network is really closed */
1604 NetworkClientConnectGame(_settings_client.network.last_joined, COMPANY_SPECTATOR);
1605 }
1606 /* Singleplayer */
1607 StateGameLoop();
1608 }
1609
1610 if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1611
1612 SoundDriver::GetInstance()->MainLoop();
1613 MusicLoop();
1614 SocialIntegration::RunCallbacks();
1615 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
game.hpp
AI::Uninitialize
static void Uninitialize(bool keepConfig)
Uninitialize the AI system.
Definition: ai_core.cpp:176
WC_SAVELOAD
@ WC_SAVELOAD
Saveload window; Window numbers:
Definition: window_type.h:144
openttd_main
int openttd_main(int argc, char *argv[])
Main entry point for this lovely game.
Definition: openttd.cpp:518
AfterNewGRFScan::save_config
bool save_config
The save config setting.
Definition: openttd.cpp:390
LinkGraphSchedule::Clear
static void Clear()
Clear all link graphs and jobs from the schedule.
Definition: linkgraphschedule.cpp:121
SaveLoadVersion
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
Definition: saveload.h:30
AfterNewGRFScan::startyear
TimerGameCalendar::Year startyear
The start year.
Definition: openttd.cpp:383
DeterminePaths
void DeterminePaths(const char *exe, bool only_local_path)
Acquire the base paths (personal dir and game data dir), fill all other paths (save dir,...
Definition: fileio.cpp:962
DriverFactoryBase::ShutdownDrivers
static void ShutdownDrivers()
Shuts down all active drivers.
Definition: driver.h:123
SwitchMode
SwitchMode
Mode which defines what mode we're switching to.
Definition: openttd.h:26
CheckEngines
void CheckEngines()
Check for engines that have an appropriate availability.
Definition: engine.cpp:1285
social_integration.h
factory.hpp
FormatArrayAsHex
std::string FormatArrayAsHex(std::span< const byte > data)
Format a byte array into a continuous hex string.
Definition: string.cpp:88
AIConfig
Definition: ai_config.hpp:16
EngineOverrideManager::ResetToCurrentNewGRFConfig
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
Definition: engine.cpp:549
GameSettings::ai_config
class AIConfig * ai_config[MAX_COMPANIES]
settings per company
Definition: settings_type.h:623
FT_SCENARIO
@ FT_SCENARIO
old or new scenario
Definition: fileio_type.h:19
Pool::PoolItem<&_company_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:335
SettingsDisableElrail
void SettingsDisableElrail(int32_t new_value)
_settings_game.disable_elrail callback
Definition: elrail.cpp:598
LoadCheckData::error_msg
std::string error_msg
Data to pass to SetDParamStr when displaying error.
Definition: fios.h:36
SAVE_DIR
@ SAVE_DIR
Base directory for all savegames.
Definition: fileio_type.h:110
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3082
ShowNetworkAskSurvey
void ShowNetworkAskSurvey()
Show a modal confirmation window with "no" / "preview" / "yes" buttons.
Definition: network_gui.cpp:2566
SM_START_HEIGHTMAP
@ SM_START_HEIGHTMAP
Load a heightmap and start a new game from it.
Definition: openttd.h:38
train.h
SM_LOAD_GAME
@ SM_LOAD_GAME
Load game, Play Scenario.
Definition: openttd.h:32
Dimension
Dimensions (a width and height) of a rectangle in 2D.
Definition: geometry_type.hpp:30
command_func.h
ShowErrorMessage
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
Definition: error_gui.cpp:367
ErrorMessageData::SetDParamStr
void SetDParamStr(uint n, const char *str)
Set a rawstring parameter.
Definition: error_gui.cpp:146
DoStartupNewCompany
Company * DoStartupNewCompany(bool is_ai, CompanyID company=INVALID_COMPANY)
Create a new company and sets all company variables default values.
Definition: company_cmd.cpp:582
DoExitSave
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:3146
AfterNewGRFScan::join_server_password
std::string join_server_password
The password to join the server with.
Definition: openttd.cpp:388
ScheduleErrorMessage
void ScheduleErrorMessage(ErrorList &datas)
Schedule a list of errors.
Definition: error_gui.cpp:452
BaseMedia< GraphicsSet >::SetSet
static bool SetSet(const GraphicsSet *set)
Set the set to be used.
Definition: base_media_func.h:241
_config_file
std::string _config_file
Configuration file of OpenTTD.
Definition: settings.cpp:58
Backup
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
TimerGameConst< struct Calendar >::INVALID_YEAR
static constexpr TimerGame< struct Calendar >::Year INVALID_YEAR
Representation of an invalid year.
Definition: timer_game_common.h:192
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:627
timer_game_calendar.h
GUISettings::autosave_on_exit
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?...
Definition: settings_type.h:163
BLT_8BPP
@ BLT_8BPP
Base set has 8 bpp sprites only.
Definition: base_media_base.h:253
CheckIndustries
void CheckIndustries()
Verify whether the generated industries are complete, and warn the user if not.
Definition: industry_cmd.cpp:3079
_gamelog
Gamelog _gamelog
Gamelog instance.
Definition: gamelog.cpp:31
Station
Station data structure.
Definition: station_base.h:442
_autosave_interval
static IntervalTimer< TimerGameRealtime > _autosave_interval({std::chrono::milliseconds::zero(), TimerGameRealtime::AUTOSAVE}, [](auto) { _pause_mode &=~PM_COMMAND_DURING_PAUSE;_do_autosave=true;SetWindowDirty(WC_STATUS_BAR, 0);static FiosNumberedSaveName _autosave_ctr("autosave");DoAutoOrNetsave(_autosave_ctr);_do_autosave=false;SetWindowDirty(WC_STATUS_BAR, 0);})
Interval for regular autosaves.
BASESET_DIR
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:116
TarScanner::DoScan
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
Definition: fileio.cpp:427
elrail_func.h
SaveOrLoad
SaveOrLoadResult SaveOrLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
Definition: saveload.cpp:3037
MusicDriver::SetVolume
virtual void SetVolume(byte vol)=0
Set the volume, if possible.
SoundDriver::MainLoop
virtual void MainLoop()
Called once every tick.
Definition: sound_driver.hpp:19
SM_EDITOR
@ SM_EDITOR
Switch to scenario editor.
Definition: openttd.h:31
NetworkSettings::default_company_pass
std::string default_company_pass
default password for new companies in encrypted form
Definition: settings_type.h:319
_network_server
bool _network_server
network-server is active
Definition: network.cpp:60
BaseSet::name
std::string name
The name of the base set.
Definition: base_media_base.h:61
SaveLoadOperation
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:47
FileToSaveLoad::name
std::string name
Name of the file.
Definition: saveload.h:394
CloseWindowById
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition: window.cpp:1141
IntervalTimer
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition: timer.h:76
SaveToConfig
void SaveToConfig()
Save the values to the configuration file.
Definition: settings.cpp:1453
_load_check_data
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition: fios_gui.cpp:40
InitWindowSystem
void InitWindowSystem()
(re)initialize the windowing system
Definition: window.cpp:1783
_old_vds
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Definition: settings.cpp:57
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:234
AfterNewGRFScan::dedicated_port
uint16_t dedicated_port
Port for the dedicated server.
Definition: openttd.cpp:386
GenerateWorldSetCallback
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done.
Definition: genworld.cpp:225
_skip_all_newgrf_scanning
int _skip_all_newgrf_scanning
Set this flag to prevent any NewGRF scanning from being done.
Definition: newgrf_config.cpp:525
PFE_GL_ROADVEHS
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
Definition: framerate_type.h:52
BlitterFactory::SelectBlitter
static Blitter * SelectBlitter(const std::string &name)
Find the requested blitter and return its class.
Definition: factory.hpp:96
DriverFactoryBase::GetDriversInfo
static void GetDriversInfo(std::back_insert_iterator< std::string > &output_iterator)
Build a human readable list of available drivers, grouped by type.
Definition: driver.cpp:226
SLO_CHECK
@ SLO_CHECK
Load file for checking and/or preview.
Definition: fileio_type.h:48
misc_cmd.h
ChangeNetworkRestartTime
void ChangeNetworkRestartTime(bool reset)
Reset the automatic network restart time interval.
Definition: network_server.cpp:1880
ship.h
PerformanceMeasurer
RAII class for measuring simple elements of performance.
Definition: framerate_type.h:92
_do_autosave
bool _do_autosave
are we doing an autosave at the moment?
Definition: saveload.cpp:66
CompanySettings::vehicle
VehicleDefaultSettings vehicle
default settings for vehicles
Definition: settings_type.h:613
Gamelog::Info
void Info(uint32_t *last_ottd_rev, byte *ever_modified, bool *removed_newgrfs)
Get some basic information from the given gamelog.
Definition: gamelog.cpp:685
SetLocalCompany
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
Definition: company_cmd.cpp:114
UnInitWindowSystem
void UnInitWindowSystem()
Close down the windowing system.
Definition: window.cpp:1805
DFT_GAME_FILE
@ DFT_GAME_FILE
Save game or scenario file.
Definition: fileio_type.h:31
GameSettings::game_config
class GameConfig * game_config
settings for gamescript
Definition: settings_type.h:624
DumpDebugFacilityNames
void DumpDebugFacilityNames(std::back_insert_iterator< std::string > &output_iterator)
Dump the available debug facility names in the help text.
Definition: debug.cpp:89
LoadCheckData::grfconfig
GRFConfig * grfconfig
NewGrf configuration from save.
Definition: fios.h:45
StationCargoList
CargoList that is used for stations.
Definition: cargopacket.h:529
HandleBootstrap
bool HandleBootstrap()
Handle all procedures for bootstrapping OpenTTD without a base graphics set.
Definition: bootstrap_gui.cpp:362
RequestNewGRFScan
bool RequestNewGRFScan(NewGRFScanCallback *callback)
Request a new NewGRF scan.
Definition: openttd.cpp:1546
saveload.h
aircraft.h
SocialIntegration::EventEnterSingleplayer
static void EventEnterSingleplayer(uint map_width, uint map_height)
Event: user entered a singleplayer game.
Definition: social_integration.cpp:227
base_media_base.h
TimerGameEconomy::date_fract
static DateFract date_fract
Fractional part of the day.
Definition: timer_game_economy.h:38
BaseMedia< GraphicsSet >::SetSetByShortname
static bool SetSetByShortname(uint32_t shortname)
Set the set to be used.
Definition: base_media_func.h:278
AUTOSAVE_DIR
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
Definition: fileio_type.h:111
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:54
_network_bind_list
StringList _network_bind_list
The addresses to bind on.
Definition: network.cpp:68
GetDetailedFileType
DetailedFileType GetDetailedFileType(FiosType fios_type)
Extract the detailed file type from a FiosType.
Definition: fileio_type.h:100
NetworkBackgroundLoop
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
Definition: network.cpp:1037
SetDebugString
void SetDebugString(const char *s, void(*error_func)(const std::string &))
Set debugging levels by parsing the text in s.
Definition: debug.cpp:145
LoadFromHighScore
void LoadFromHighScore()
Initialize the highscore table to 0 and if any file exists, load in values.
Definition: highscore.cpp:145
town.h
OrthogonalTileArea::Add
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Definition: tilearea.cpp:43
StrongType::Typedef
Templated helper to make a type-safe 'typedef' representing a single POD value.
Definition: strong_typedef_type.hpp:150
RunVehicleCalendarDayProc
void RunVehicleCalendarDayProc()
Age all vehicles, spreading out the action using the current TimerGameCalendar::date_fract.
Definition: vehicle.cpp:933
LoadCheckData::HasErrors
bool HasErrors()
Check whether loading the game resulted in errors.
Definition: fios.h:59
Gamelog::Reset
void Reset()
Resets and frees all memory allocated - used before loading or starting a new game.
Definition: gamelog.cpp:94
DIAGDIR_NW
@ DIAGDIR_NW
Northwest.
Definition: direction_type.h:78
Company::infrastructure
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
Definition: company_base.h:129
network_gui.h
GRFLoadedFeatures::used_liveries
uint64_t used_liveries
Bitmask of LiveryScheme used by the defined engines.
Definition: newgrf.h:179
_display_opt
byte _display_opt
What do we want to draw/do?
Definition: transparency_gui.cpp:26
GETOPT_SHORT_NOVAL
#define GETOPT_SHORT_NOVAL(shortname)
Short option without value.
Definition: getoptdata.h:91
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:240
Industry
Defines the internal data of a functional industry.
Definition: industry.h:68
AfterNewGRFScan::AfterNewGRFScan
AfterNewGRFScan()
Create a new callback.
Definition: openttd.cpp:395
SM_LOAD_SCENARIO
@ SM_LOAD_SCENARIO
Load scenario from scenario editor.
Definition: openttd.h:37
gamelog.h
fios.h
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
StrEmpty
bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:56
CheckCaches
static void CheckCaches()
Check the validity of some of the caches.
Definition: openttd.cpp:1238
genworld.h
MakeHeightmapScreenshot
bool MakeHeightmapScreenshot(const char *filename)
Make a heightmap of the current map.
Definition: screenshot.cpp:839
OrthogonalTileArea::h
uint16_t h
The height of the area.
Definition: tilearea_type.h:21
InitializeScreenshotFormats
void InitializeScreenshotFormats()
Initialize screenshot format information on startup, with _screenshot_format_name filled from the loa...
Definition: screenshot.cpp:585
PFE_GL_LANDSCAPE
@ PFE_GL_LANDSCAPE
Time spent processing other world features.
Definition: framerate_type.h:55
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
GCF_COMPATIBLE
@ GCF_COMPATIBLE
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches)
Definition: newgrf_config.h:26
_ini_musicdriver
std::string _ini_musicdriver
The music driver a stored in the configuration file.
Definition: driver.cpp:37
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:619
BaseMedia< GraphicsSet >::GetSetsList
static void GetSetsList(std::back_insert_iterator< std::string > &output_iterator)
Returns a list with the sets.
Definition: base_media_func.h:297
SpecializedStation< Station, false >::Iterate
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Definition: base_station_base.h:310
ai.hpp
PFE_GL_TRAINS
@ PFE_GL_TRAINS
Time spent processing trains.
Definition: framerate_type.h:51
UninitFontCache
void UninitFontCache()
Free everything allocated w.r.t.
Definition: fontcache.cpp:224
NetworkChangeCompanyPassword
std::string NetworkChangeCompanyPassword(CompanyID company_id, std::string password)
Change the company password of a given company.
Definition: network.cpp:157
VehicleCargoList
CargoList that is used for vehicles.
Definition: cargopacket.h:351
screenshot.h
GETOPT_SHORT_OPTVAL
#define GETOPT_SHORT_OPTVAL(shortname)
Short option with optional value.
Definition: getoptdata.h:104
PM_UNPAUSED
@ PM_UNPAUSED
A normal unpaused game.
Definition: openttd.h:63
Ship::UpdateCache
void UpdateCache()
Update the caches of this ship.
Definition: ship_cmd.cpp:238
AdjustGUIZoom
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
Definition: gfx.cpp:1814
GoodsEntry::cargo
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition: station_base.h:210
COMPANY_FIRST
@ COMPANY_FIRST
First company, same as owner.
Definition: company_type.h:22
company_cmd.h
DO_FULL_ANIMATION
@ DO_FULL_ANIMATION
Perform palette animation.
Definition: openttd.h:49
NetworkClientJoinGame
void NetworkClientJoinGame()
Actually perform the joining to the server.
Definition: network.cpp:806
FileToSaveLoad::abstract_ftype
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Definition: saveload.h:393
_company_colours
Colours _company_colours[MAX_COMPANIES]
NOSAVE: can be determined from company structs.
Definition: company_cmd.cpp:51
error_func.h
OnStartGame
static void OnStartGame(bool dedicated_server)
Triggers everything that should be triggered when starting a game.
Definition: openttd.cpp:862
RebuildTownCaches
void RebuildTownCaches()
Rebuild all the cached variables of towns.
Definition: town_sl.cpp:30
COMPANY_NEW_COMPANY
@ COMPANY_NEW_COMPANY
The client wants a new company.
Definition: company_type.h:34
SLO_LOAD
@ SLO_LOAD
File is being loaded.
Definition: fileio_type.h:49
GroundVehicleCache
Cached, frequently calculated values.
Definition: ground_vehicle.hpp:29
IsBayRoadStopTile
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
Definition: station_map.h:223
GWM_HEIGHTMAP
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
Definition: genworld.h:31
NetworkSettings::last_joined
std::string last_joined
Last joined server.
Definition: settings_type.h:332
SLO_SAVE
@ SLO_SAVE
File is being saved.
Definition: fileio_type.h:50
settings_func.h
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:147
PM_PAUSED_SAVELOAD
@ PM_PAUSED_SAVELOAD
A game paused for saving/loading.
Definition: openttd.h:65
MusicDriver::GetInstance
static MusicDriver * GetInstance()
Get the currently active instance of the music driver.
Definition: music_driver.hpp:46
SM_NEWGAME
@ SM_NEWGAME
New Game --> 'Random game'.
Definition: openttd.h:28
S8BPP_NONE
@ S8BPP_NONE
No support for 8bpp by OS or hardware, force 32bpp blitters.
Definition: gfx_type.h:331
roadstop_base.h
free
void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:379
SM_SAVE_HEIGHTMAP
@ SM_SAVE_HEIGHTMAP
Save heightmap.
Definition: openttd.h:35
highscore.h
AfterLoadCompanyStats
void AfterLoadCompanyStats()
Rebuilding of company statistics after loading a savegame.
Definition: company_sl.cpp:96
timer_game_realtime.h
IConsoleCmdExec
void IConsoleCmdExec(const std::string &command_string, const uint recurse_count)
Execute a given command passed to us.
Definition: console.cpp:293
GetSaveLoadErrorString
const char * GetSaveLoadErrorString()
Get the string representation of the error message.
Definition: saveload.cpp:2749
Game::GetConsoleList
static void GetConsoleList(std::back_insert_iterator< std::string > &output_iterator, bool newest_only)
Wrapper function for GameScanner::GetConsoleList.
Definition: game_core.cpp:223
VS_CRASHED
@ VS_CRASHED
Vehicle is crashed.
Definition: vehicle_base.h:40
GWM_RANDOM
@ GWM_RANDOM
Generate a random map for SE.
Definition: genworld.h:30
GameConfig
Definition: game_config.hpp:15
CompanyProperties::colour
Colours colour
Company colour.
Definition: company_base.h:72
ShowHelp
static void ShowHelp()
Show the help message when someone passed a wrong parameter.
Definition: openttd.cpp:149
PFE_GL_SHIPS
@ PFE_GL_SHIPS
Time spent processing ships.
Definition: framerate_type.h:53
GETOPT_END
#define GETOPT_END()
Option terminator.
Definition: getoptdata.h:107
InitFontCache
void InitFontCache(bool monospace)
(Re)initialize the font cache related things, i.e.
Definition: fontcache.cpp:197
ParseResolution
static void ParseResolution(Dimension *res, const char *s)
Extract the resolution from the given string and store it in the 'res' parameter.
Definition: openttd.cpp:270
GUISettings::pause_on_newgame
bool pause_on_newgame
whether to start new games paused or not
Definition: settings_type.h:173
CargoList::InvalidateCache
void InvalidateCache()
Invalidates the cached data and rebuilds it.
Definition: cargopacket.cpp:210
SL_REINIT
@ SL_REINIT
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
Definition: saveload.h:386
OnStartScenario
static void OnStartScenario()
Triggers everything required to set up a saved scenario for a new game.
Definition: openttd.cpp:847
GroundVehicle::gcache
GroundVehicleCache gcache
Cache of often calculated values.
Definition: ground_vehicle.hpp:80
OrthogonalTileArea
Represents the covered area of e.g.
Definition: tilearea_type.h:18
_pause_mode
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:50
road_gui.h
AI::Initialize
static void Initialize()
Initialize the AI system.
Definition: ai_core.cpp:162
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:55
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition: company_base.h:105
HasModalProgress
bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition: progress.h:17
PSM_ENTER_GAMELOOP
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
Definition: newgrf_storage.h:21
timer_game_tick.h
ShutdownGame
static void ShutdownGame()
Uninitializes drivers, frees allocated memory, cleans pools, ...
Definition: openttd.cpp:287
VehicleCache
Cached often queried values common to all vehicles.
Definition: vehicle_base.h:123
MAX_COMPANIES
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:49
industry.h
safeguards.h
timer.h
MemCmpT
int MemCmpT(const T *ptr1, const T *ptr2, size_t num=1)
Type-safe version of memcmp().
Definition: mem_func.hpp:63
GameCreationSettings::starting_year
TimerGameCalendar::Year starting_year
starting date
Definition: settings_type.h:341
music_driver.hpp
FiosGetSavegameListCallback
std::tuple< FiosType, std::string > FiosGetSavegameListCallback(SaveLoadOperation fop, const std::string &file, const std::string_view ext)
Callback for FiosGetFileList.
Definition: fios.cpp:444
SaveHotkeysToConfig
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
Definition: hotkeys.cpp:346
CursorVars::fix_at
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
Definition: gfx_type.h:120
PoolBase::Clean
static void Clean(PoolType)
Clean all pools of given type.
Definition: pool_func.cpp:30
FT_INVALID
@ FT_INVALID
Invalid or unknown file type.
Definition: fileio_type.h:22
NetworkShutDown
void NetworkShutDown()
This shuts the network down.
Definition: network.cpp:1256
_switch_mode_time
std::chrono::steady_clock::time_point _switch_mode_time
The time when the switch mode was requested.
Definition: gfx.cpp:49
Game::Uninitialize
static void Uninitialize(bool keepConfig)
Uninitialize the Game system.
Definition: game_core.cpp:103
AfterNewGRFScan::OnNewGRFsScanned
void OnNewGRFsScanned() override
Called whenever the NewGRF scan completed.
Definition: openttd.cpp:402
AfterNewGRFScan::generation_seed
uint32_t generation_seed
Seed for the new game.
Definition: openttd.cpp:384
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:59
ChangeAutosaveFrequency
void ChangeAutosaveFrequency(bool reset)
Reset the interval of the autosave.
Definition: openttd.cpp:1533
GetOptData::opt
char * opt
Option value, if available (else nullptr).
Definition: getoptdata.h:31
gfx_layout.h
GRFConfig::IsCompatible
bool IsCompatible(uint32_t old_version) const
Return whether this NewGRF can replace an older version of the same NewGRF.
Definition: newgrf_config.cpp:78
ScanNewGRFFiles
void ScanNewGRFFiles(NewGRFScanCallback *callback)
Scan for all NewGRFs.
Definition: newgrf_config.cpp:672
ErrorMessageData
The data of the error message.
Definition: error.h:31
DFT_OLD_GAME_FILE
@ DFT_OLD_GAME_FILE
Old save game or scenario file.
Definition: fileio_type.h:30
error.h
TimerManager
The TimerManager manages a single Timer-type.
Definition: timer_manager.h:27
PFE_GL_AIRCRAFT
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
Definition: framerate_type.h:54
_loaded_newgrf_features
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition: newgrf.cpp:82
TimerManager::Elapsed
static bool Elapsed(TElapsed value)
Called when time for this timer elapsed.
DoAutoOrNetsave
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
Definition: saveload.cpp:3128
network_server.h
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:62
AI::GameLoop
static void GameLoop()
Called every game-tick to let AIs do something.
Definition: ai_core.cpp:70
SocialIntegration::Shutdown
static void Shutdown()
Shutdown the social integration system, and all social integration plugins that are loaded.
Definition: social_integration.cpp:184
WindowDesc::SaveToConfig
static void SaveToConfig()
Save all WindowDesc settings to _windows_file.
Definition: window.cpp:178
linkgraphschedule.h
stdafx.h
FT_SAVEGAME
@ FT_SAVEGAME
old or new savegame
Definition: fileio_type.h:18
GameMode
GameMode
Mode which defines the state of the game.
Definition: openttd.h:18
SM_GENRANDLAND
@ SM_GENRANDLAND
Generate random land within scenario editor.
Definition: openttd.h:36
SM_SAVE_GAME
@ SM_SAVE_GAME
Save game.
Definition: openttd.h:34
OptionData
Data of an option.
Definition: getoptdata.h:22
BaseMusic::ini_set
static std::string ini_set
The set as saved in the config file.
Definition: base_media_base.h:350
NetworkSurveyHandler::Transmit
void Transmit(Reason reason, bool blocking=false)
Transmit the survey.
Definition: network_survey.cpp:87
VideoDriver::GetInstance
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Definition: video_driver.hpp:200
SocialIntegration::EventEnterMultiplayer
static void EventEnterMultiplayer(uint map_width, uint map_height)
Event: user entered a multiplayer game.
Definition: social_integration.cpp:234
GetOptData
Data storage for parsing command line options.
Definition: getoptdata.h:30
viewport_func.h
NetworkDisconnect
void NetworkDisconnect(bool close_admins)
We want to disconnect from the host/clients.
Definition: network.cpp:956
PerformanceMeasurer::Paused
static void Paused(PerformanceElement elem)
Indicate that a cycle of "pause" where no processing occurs.
Definition: framerate_gui.cpp:297
LoadCheckData::error
StringID error
Error message from loading. INVALID_STRING_ID if no error.
Definition: fios.h:35
NetworkSettings::server_port
uint16_t server_port
port the server listens on
Definition: settings_type.h:308
animated_tile_func.h
Layouter::ReduceLineCache
static void ReduceLineCache()
Reduce the size of linecache if necessary to prevent infinite growth.
Definition: gfx_layout.cpp:403
PT_ALL
@ PT_ALL
All pool types.
Definition: pool_type.hpp:22
AfterNewGRFScan::join_company_password
std::string join_company_password
The password to join the company with.
Definition: openttd.cpp:389
GENERATE_NEW_SEED
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:24
ObjectSpec::name
StringID name
The name for this object.
Definition: newgrf_object.h:65
GraphicsSet::GetOrCreateExtraConfig
GRFConfig & GetOrCreateExtraConfig() const
Return configuration for the extra GRF, or lazily create it.
Definition: gfxinit.cpp:374
UpdateAircraftCache
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
Definition: aircraft_cmd.cpp:602
SM_LOAD_HEIGHTMAP
@ SM_LOAD_HEIGHTMAP
Load heightmap from scenario editor.
Definition: openttd.h:39
sound_driver.hpp
Map::SizeX
static debug_inline uint SizeX()
Get the size of the map along the X.
Definition: map_func.h:270
SafeLoad
bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, std::shared_ptr< LoadFilter > lf=nullptr)
Load the specified savegame but on error do different things.
Definition: openttd.cpp:969
_blitter_autodetected
bool _blitter_autodetected
Was the blitter autodetected or specified by the user?
Definition: driver.cpp:40
DFT_INVALID
@ DFT_INVALID
Unknown or invalid file.
Definition: fileio_type.h:43
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:48
SocialIntegration::EventEnterScenarioEditor
static void EventEnterScenarioEditor(uint map_width, uint map_height)
Event: user entered the Scenario Editor.
Definition: social_integration.cpp:220
rail_gui.h
BaseMedia< GraphicsSet >::SetSetByName
static bool SetSetByName(const std::string &name)
Set the set to be used.
Definition: base_media_func.h:258
GoodsEntry
Stores station stats for a single cargo.
Definition: station_base.h:166
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:50
vehicle_func.h
rev.h
UpdateNewGRFConfigPalette
void UpdateNewGRFConfigPalette(int32_t)
Update the palettes of the graphics from the config file.
Definition: newgrf_config.cpp:243
Game::GameLoop
static void GameLoop()
Called every game-tick to let Game do something.
Definition: game_core.cpp:31
station_base.h
Driver::DT_SOUND
@ DT_SOUND
A sound driver.
Definition: driver.h:41
TarScanner::SCENARIO
@ SCENARIO
Scan for scenarios and heightmaps.
Definition: fileio_func.h:68
Pool::PoolItem<&_industry_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:384
strings_func.h
TimerGameEconomy::year
static Year year
Current year, starting at 0.
Definition: timer_game_economy.h:35
SocialIntegration::EventJoiningMultiplayer
static void EventJoiningMultiplayer()
Event: user is joining a multiplayer game.
Definition: social_integration.cpp:241
PFE_GAMELOOP
@ PFE_GAMELOOP
Speed of gameloop processing.
Definition: framerate_type.h:49
FiosNumberedSaveName
A savegame name automatically numbered.
Definition: fios.h:129
AI::KillAll
static void KillAll()
Kill any and all AIs we manage.
Definition: ai_core.cpp:152
DetailedFileType
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:28
LoadCheckData::Clear
void Clear()
Reset read data.
Definition: fios_gui.cpp:48
GameCreationSettings::generation_seed
uint32_t generation_seed
noise seed for world generation
Definition: settings_type.h:340
RoadVehUpdateCache
void RoadVehUpdateCache(RoadVehicle *v, bool same_length=false)
Update the cache of a road vehicle.
Definition: roadveh_cmd.cpp:219
PFE_GL_ECONOMY
@ PFE_GL_ECONOMY
Time spent processing cargo movement.
Definition: framerate_type.h:50
subsidy_func.h
SaveToHighScore
void SaveToHighScore()
Save HighScore table to file.
Definition: highscore.cpp:123
RebuildSubsidisedSourceAndDestinationCache
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition: subsidy.cpp:135
FillNewGRFVehicleCache
void FillNewGRFVehicleCache(const Vehicle *v)
Fill the grf_cache of the given vehicle.
Definition: newgrf_engine.cpp:1382
SocialIntegration::EventEnterMainMenu
static void EventEnterMainMenu()
Event: user entered the main menu.
Definition: social_integration.cpp:213
IsDockingTile
bool IsDockingTile(Tile t)
Checks whether the tile is marked as a dockling tile.
Definition: water_map.h:374
GameCreationSettings::map_y
uint8_t map_y
Y size of map.
Definition: settings_type.h:344
Backup::Restore
void Restore()
Restore the variable.
Definition: backup_type.hpp:112
GameCreationSettings::map_x
uint8_t map_x
X size of map.
Definition: settings_type.h:343
NetworkSurveyHandler::Reason::LEAVE
@ LEAVE
User is leaving the game (but not exiting the application).
_ini_blitter
std::string _ini_blitter
The blitter as stored in the configuration file.
Definition: driver.cpp:39
BaseGraphics::Ini::extra_version
uint32_t extra_version
version of the extra GRF
Definition: base_media_base.h:286
SpecializedVehicle< Train, Type >::From
static Train * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1201
Train::ConsistChanged
void ConsistChanged(ConsistChangeFlags allowed_changes)
Recalculates the cached stuff of a train.
Definition: train_cmd.cpp:111
CrashLog::SetErrorMessage
static void SetErrorMessage(const std::string &message)
Sets a message for the error message handler.
Definition: crashlog.cpp:323
video_driver.hpp
NO_DIRECTORY
@ NO_DIRECTORY
A path without any base directory.
Definition: fileio_type.h:126
COMPANY_SPECTATOR
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
GUISettings::autosave_interval
uint32_t autosave_interval
how often should we do autosaves?
Definition: settings_type.h:160
OrthogonalTileArea::tile
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
Driver::DT_VIDEO
@ DT_VIDEO
A video driver.
Definition: driver.h:42
framerate_type.h
_file_to_saveload
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:60
GenerateSavegameId
void GenerateSavegameId()
Generate an unique savegame ID.
Definition: misc.cpp:90
GRFConfig::next
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Definition: newgrf_config.h:174
_ini_sounddriver
std::string _ini_sounddriver
The sound driver a stored in the configuration file.
Definition: driver.cpp:35
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
PM_PAUSED_NORMAL
@ PM_PAUSED_NORMAL
A game normally paused.
Definition: openttd.h:64
_options
static const OptionData _options[]
Options of OpenTTD.
Definition: openttd.cpp:482
GWM_EMPTY
@ GWM_EMPTY
Generate an empty map (sea-level)
Definition: genworld.h:29
FatalErrorI
void FatalErrorI(const std::string &str)
Error handling for fatal non-user errors.
Definition: openttd.cpp:135
FiosGetScenarioListCallback
std::tuple< FiosType, std::string > FiosGetScenarioListCallback(SaveLoadOperation fop, const std::string &file, const std::string_view ext)
Callback for FiosGetFileList.
Definition: fios.cpp:493
newgrf.h
SocialIntegration::RunCallbacks
static void RunCallbacks()
Allow any social integration library to handle their own events.
Definition: social_integration.cpp:194
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition: strings.cpp:327
SM_RESTART_HEIGHTMAP
@ SM_RESTART_HEIGHTMAP
Load a heightmap and start a new game from it with current settings.
Definition: openttd.h:40
BaseMedia< GraphicsSet >::FindSets
static uint FindSets()
Do the scan for files.
Definition: base_media_base.h:198
PFE_ALLSCRIPTS
@ PFE_ALLSCRIPTS
Sum of all GS/AI scripts.
Definition: framerate_type.h:61
VehicleSettings::disable_elrails
bool disable_elrails
when true, the elrails are disabled
Definition: settings_type.h:523
GetFirstPlayableCompanyID
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
Definition: company_cmd.cpp:1279
progress.h
DebugSendRemoteMessages
void DebugSendRemoteMessages()
Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the GameLoop threa...
Definition: debug.cpp:244
CallWindowGameTickEvent
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
Definition: window.cpp:3229
FT_HEIGHTMAP
@ FT_HEIGHTMAP
heightmap file
Definition: fileio_type.h:20
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
SetDParamStr
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:352
ResetNewGRFData
void ResetNewGRFData()
Reset all NewGRF loaded data.
Definition: newgrf.cpp:8773
SaveOrLoadResult
SaveOrLoadResult
Save or load result codes.
Definition: saveload.h:383
company_func.h
WL_ERROR
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition: error.h:26
SM_RELOADGAME
@ SM_RELOADGAME
Reload the savegame / scenario / heightmap you started the game with.
Definition: openttd.h:30
SM_MENU
@ SM_MENU
Switch to game intro menu.
Definition: openttd.h:33
SocialIntegration::Initialize
static void Initialize()
Initialize the social integration system, loading any social integration plugins that are available.
Definition: social_integration.cpp:160
GUISettings::starting_colour
Colours starting_colour
default color scheme for the company to start a new game with
Definition: settings_type.h:196
GUISettings::last_newgrf_count
uint32_t last_newgrf_count
the numbers of NewGRFs we found during the last scan
Definition: settings_type.h:192
OrthogonalTileArea::w
uint16_t w
The width of the area.
Definition: tilearea_type.h:20
AnimateAnimatedTiles
void AnimateAnimatedTiles()
Animate all tiles in the animated tile list, i.e. call AnimateTile on them.
Definition: animated_tile.cpp:49
GWM_NEWGAME
@ GWM_NEWGAME
Generate a map for a new game.
Definition: genworld.h:28
GetOptData::GetOpt
int GetOpt()
Find the next option.
Definition: getoptdata.cpp:22
DriverFactoryBase::SelectDriver
static void SelectDriver(const std::string &name, Driver::Type type)
Find the requested driver and return its class.
Definition: driver.cpp:94
AfterNewGRFScan
Callback structure of statements to be executed after the NewGRF scan.
Definition: openttd.cpp:382
network.h
MusicLoop
void MusicLoop()
Check music playback status and start/stop/song-finished.
Definition: music_gui.cpp:454
CommandHelper
Definition: command_func.h:93
NetworkClientConnectGame
bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password, const std::string &join_company_password)
Join a client to the server at with the given connection string.
Definition: network.cpp:772
CheckForMissingGlyphs
void CheckForMissingGlyphs(bool base_font, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
Definition: strings.cpp:2268
SLO_INVALID
@ SLO_INVALID
Unknown file operation.
Definition: fileio_type.h:52
NewGRFScanCallback
Callback for NewGRF scanning.
Definition: newgrf_config.h:206
Town
Town data structure.
Definition: town.h:50
TrainCache
Variables that are cached to improve performance and such.
Definition: train.h:72
MusicSettings::effect_vol
byte effect_vol
The requested effects volume.
Definition: settings_type.h:251
WindowDesc::LoadFromConfig
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
Definition: window.cpp:156
LoadWithFilter
SaveOrLoadResult LoadWithFilter(std::shared_ptr< LoadFilter > reader)
Load the game using a (reader) filter.
Definition: saveload.cpp:3017
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1552
ClientSettings::network
NetworkSettings network
settings related to the network
Definition: settings_type.h:637
random_func.hpp
LoadHotkeysFromConfig
void LoadHotkeysFromConfig()
Load the hotkeys from the config file.
Definition: hotkeys.cpp:340
VideoDriver::MainLoop
virtual void MainLoop()=0
Perform the actual drawing.
GUISettings::starting_colour_secondary
Colours starting_colour_secondary
default secondary color scheme for the company to start a new game with
Definition: settings_type.h:197
ParseFullConnectionString
std::string_view ParseFullConnectionString(const std::string &connection_string, uint16_t &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
Definition: network.cpp:504
TarScanner::BASESET
@ BASESET
Scan for base sets.
Definition: fileio_func.h:65
GenerateWorld
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
Definition: genworld.cpp:277
SoundDriver::GetInstance
static SoundDriver * GetInstance()
Get the currently active instance of the sound driver.
Definition: sound_driver.hpp:35
UserErrorI
void UserErrorI(const std::string &str)
Error handling for fatal user errors.
Definition: openttd.cpp:114
GetAbstractFileType
AbstractFileType GetAbstractFileType(FiosType fios_type)
Extract the abstract file type from a FiosType.
Definition: fileio_type.h:90
PSM_LEAVE_GAMELOOP
@ PSM_LEAVE_GAMELOOP
Leave the gameloop, changes will be temporary.
Definition: newgrf_storage.h:22
INVALID_COMPANY
@ INVALID_COMPANY
An invalid company.
Definition: company_type.h:30
crashlog.h
BasePersistentStorageArray::SwitchMode
static void SwitchMode(PersistentStorageMode mode, bool ignore_prev_mode=false)
Clear temporary changes made since the last call to SwitchMode, and set whether subsequent changes sh...
Definition: newgrf_storage.cpp:54
BlitterFactory::GetBlittersInfo
static void GetBlittersInfo(std::back_insert_iterator< std::string > &output_iterator)
Fill a buffer with information about the blitters.
Definition: factory.hpp:149
fontcache.h
PerformanceAccumulator::Reset
static void Reset(PerformanceElement elem)
Store the previous accumulator value and reset for a new cycle of accumulating measurements.
Definition: framerate_gui.cpp:327
ProcessAsyncSaveFinish
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition: saveload.cpp:387
InitializeRailGUI
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
Definition: rail_gui.cpp:2357
ResetWindowSystem
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition: window.cpp:1819
gui.h
LoadIntroGame
static void LoadIntroGame(bool load_newgrfs=true)
Load the introduction game.
Definition: openttd.cpp:318
ZOOM_LVL_NORMAL
@ ZOOM_LVL_NORMAL
The normal zoom level.
Definition: zoom_type.h:22
AfterNewGRFScan::connection_string
std::string connection_string
Information about the server to connect to.
Definition: openttd.cpp:387
ClientSettings::company
CompanySettings company
default values for per-company settings
Definition: settings_type.h:638
CCF_TRACK
@ CCF_TRACK
Valid changes while vehicle is driving, and possibly changing tracks.
Definition: train.h:48
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:627
AI::GetConsoleList
static void GetConsoleList(std::back_insert_iterator< std::string > &output_iterator, bool newest_only)
Wrapper function for AIScanner::GetAIConsoleList.
Definition: ai_core.cpp:293
LoadCheckData::HasNewGrfs
bool HasNewGrfs()
Check whether the game uses any NewGrfs.
Definition: fios.h:68
getoptdata.h
BaseSounds::ini_set
static std::string ini_set
The set as saved in the config file.
Definition: base_media_base.h:301
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
FileToSaveLoad::detail_ftype
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
Definition: saveload.h:392
ResetGRFConfig
void ResetGRFConfig(bool defaults)
Reset the current GRF Config to either blank or newgame settings.
Definition: newgrf_config.cpp:451
BaseMedia< GraphicsSet >::GetUsedSet
static const GraphicsSet * GetUsedSet()
Return the used set.
Definition: base_media_func.h:394
WC_STATUS_BAR
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
Definition: window_type.h:64
RoadStop
A Stop for a Road Vehicle.
Definition: roadstop_base.h:22
StateGameLoop
void StateGameLoop()
State controlling game loop.
Definition: openttd.cpp:1427
NetworkStartUp
void NetworkStartUp()
This tries to launch the network for a given OS.
Definition: network.cpp:1235
network_survey.h
InitializeSpriteSorter
void InitializeSpriteSorter()
Choose the "best" sprite sorter and set _vp_sprite_sorter.
Definition: viewport.cpp:3515
viewport_sprite_sorter.h
Driver::DT_MUSIC
@ DT_MUSIC
A music driver, needs to be before sound to properly shut down extmidi forked music players.
Definition: driver.h:40
console_func.h
AfterNewGRFScan::dedicated_host
std::string dedicated_host
Hostname for the dedicated server.
Definition: openttd.cpp:385
_network_available
bool _network_available
is network mode available?
Definition: network.cpp:61
InitializeRoadGUI
void InitializeRoadGUI()
I really don't know why rail_gui.cpp has this too, shouldn't be included in the other one?
Definition: road_gui.cpp:1787
FileToSaveLoad::SetMode
void SetMode(FiosType ft)
Set the mode and file type of the file to save or load based on the type of file entry at the file sy...
Definition: saveload.cpp:3197
NetworkSettings::reload_cfg
bool reload_cfg
reload the config file before restarting
Definition: settings_type.h:331
DIAGDIR_NE
@ DIAGDIR_NE
Northeast, upper right on your monitor.
Definition: direction_type.h:75
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
GETOPT_SHORT_VALUE
#define GETOPT_SHORT_VALUE(shortname)
Short option with value.
Definition: getoptdata.h:97
Company
Definition: company_base.h:116
game_config.hpp
IsLocalCompany
bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:47
SM_JOIN_GAME
@ SM_JOIN_GAME
Join a network game.
Definition: openttd.h:41
Driver::Stop
virtual void Stop()=0
Stop this driver.
CursorVars::in_window
bool in_window
mouse inside this window, determines drawing logic
Definition: gfx_type.h:141
ClientSettings::music
MusicSettings music
settings related to music/sound
Definition: settings_type.h:640
SL_OK
@ SL_OK
completed successfully
Definition: saveload.h:384
NetworkServerUpdateGameInfo
void NetworkServerUpdateGameInfo()
Update the server's NetworkServerGameInfo due to changes in settings.
Definition: network_server.cpp:1999
LoadFromConfig
void LoadFromConfig(bool startup)
Load the values from the configuration files.
Definition: settings.cpp:1353
PM_COMMAND_DURING_PAUSE
@ PM_COMMAND_DURING_PAUSE
A game paused, and a command executed during the pause; resets on autosave.
Definition: openttd.h:71
MusicSettings::music_vol
byte music_vol
The requested music volume.
Definition: settings_type.h:250
_sl_version
SaveLoadVersion _sl_version
the major savegame version identifier
Definition: saveload.cpp:63
UpdateLandscapingLimits
void UpdateLandscapingLimits()
Update the landscaping limits per company.
Definition: company_cmd.cpp:315
_cur_resolution
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:32
network_func.h
_is_network_server
bool _is_network_server
Does this client wants to be a network-server?
Definition: network.cpp:63
GetOptData::numleft
int numleft
Number of arguments left in argv.
Definition: getoptdata.h:32
NetworkSurveyHandler::Reason::EXIT
@ EXIT
User is exiting the application.
_network_reconnect
uint8_t _network_reconnect
Reconnect timeout.
Definition: network.cpp:67
_ini_videodriver
std::string _ini_videodriver
The video driver a stored in the configuration file.
Definition: driver.cpp:30
timer_game_economy.h
_settings_newgame
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition: settings.cpp:56
INVALID_STRING_ID
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
ResetCompanyLivery
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
Definition: company_cmd.cpp:558
Map::SizeY
static uint SizeY()
Get the size of the map along the Y.
Definition: map_func.h:279
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:636
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:27
InitializeLanguagePacks
void InitializeLanguagePacks()
Make a list of the available language packs.
Definition: strings.cpp:2110
NewGRFCache
Cached often queried (NewGRF) values.
Definition: vehicle_base.h:68
SetupColoursAndInitialWindow
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
Definition: main_gui.cpp:541
mixer.h
FileToSaveLoad::file_op
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:391
ai_config.hpp
engine_func.h
StateGameLoop_LinkGraphPauseControl
void StateGameLoop_LinkGraphPauseControl()
Pause the game if in 2 TimerGameEconomy::date_fract ticks, we would do a join with the next link grap...
Definition: linkgraphschedule.cpp:172
news_func.h
hotkeys.h
roadveh.h
TimerGameRealtime::AUTOSAVE
@ AUTOSAVE
Only run when not paused or there was a Command executed recently.
Definition: timer_game_realtime.h:33
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition: timer_game_calendar.h:32
NetworkSettings::participate_survey
ParticipateSurvey participate_survey
Participate in the automated survey.
Definition: settings_type.h:335
RunTileLoop
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every 256 ticks.
Definition: landscape.cpp:759
SM_RESTARTGAME
@ SM_RESTARTGAME
Restart --> 'Random game' with current settings.
Definition: openttd.h:29
backup_type.hpp
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition: timer_game_economy.h:37
Game::Initialize
static void Initialize()
Initialize the Game system.
Definition: game_core.cpp:57
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103