OpenTTD Source: src/openttd.cpp Source File

OpenTTD Source 15.3

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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
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 "base_media_graphics.h"
25#include "base_media_music.h"
26#include "base_media_sounds.h"
27#include "saveload/saveload.h"
28#include "company_cmd.h"
29#include "company_func.h"
30#include "company_gui.h"
31#include "command_func.h"
32#include "news_func.h"
33#include "fios.h"
34#include "aircraft.h"
35#include "roadveh.h"
36#include "train.h"
37#include "ship.h"
38#include "console_func.h"
39#include "screenshot.h"
40#include "network/network.h"
41#include "network/network_func.h"
42#include "ai/ai.hpp"
43#include "ai/ai_config.hpp"
44#include "settings_func.h"
45#include "genworld.h"
46#include "progress.h"
47#include "strings_func.h"
48#include "vehicle_func.h"
49#include "gamelog.h"
50#include "animated_tile_func.h"
51#include "roadstop_base.h"
52#include "elrail_func.h"
53#include "rev.h"
54#include "highscore.h"
55#include "station_base.h"
56#include "crashlog.h"
57#include "engine_func.h"
58#include "core/random_func.hpp"
59#include "rail_gui.h"
60#include "road_gui.h"
61#include "core/backup_type.hpp"
62#include "hotkeys.h"
63#include "newgrf.h"
64#include "misc/getoptdata.h"
65#include "game/game.hpp"
66#include "game/game_config.hpp"
67#include "town.h"
68#include "subsidy_func.h"
69#include "gfx_layout.h"
70#include "viewport_func.h"
71#include "viewport_sprite_sorter.h"
72#include "framerate_type.h"
73#include "industry.h"
74#include "network/network_gui.h"
75#include "network/network_survey.h"
76#include "misc_cmd.h"
77#include "timer/timer.h"
78#include "timer/timer_game_calendar.h"
79#include "timer/timer_game_economy.h"
80#include "timer/timer_game_realtime.h"
81#include "timer/timer_game_tick.h"
82#include "social_integration.h"
83#include "core/string_consumer.hpp"
84
85#include "linkgraph/linkgraphschedule.h"
86
87#include <system_error>
88
89#include "table/strings.h"
90
91#ifdef __EMSCRIPTEN__
92# include <emscripten.h>
93# include <emscripten/html5.h>
94#endif
95
96#include "safeguards.h"
97
98void CallLandscapeTick();
99void DoPaletteAnimations();
100void MusicLoop();
101void CallWindowGameTickEvent();
102bool HandleBootstrap();
103
104extern void CheckCaches();
105extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid());
106extern void OSOpenBrowser(const std::string &url);
107extern void ShowOSErrorBox(std::string_view buf, bool system);
108extern std::string _config_file;
109
110bool _save_config = false;
111bool _request_newgrf_scan = false;
112 NewGRFScanCallback *_request_newgrf_scan_callback = nullptr;
113
119 void UserErrorI(const std::string &str)
120{
121 ShowOSErrorBox(str, false);
122 if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
123
124#ifdef __EMSCRIPTEN__
125 emscripten_exit_pointerlock();
126 /* In effect, the game ends here. As emscripten_set_main_loop() caused
127 * the stack to be unwound, the code after MainLoop() in
128 * openttd_main() is never executed. */
129 EM_ASM(if (window["openttd_abort"]) openttd_abort());
130#endif
131
132 _exit(1);
133}
134
140 void FatalErrorI(const std::string &str)
141{
142 if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
143 ShowOSErrorBox(str, true);
144 }
145
146 /* Set the error message for the crash log and then invoke it. */
147 CrashLog::SetErrorMessage(str);
148 abort();
149}
150
154 static void ShowHelp()
155{
156 std::string str;
157 str.reserve(8192);
158
159 std::back_insert_iterator<std::string> output_iterator = std::back_inserter(str);
160 fmt::format_to(output_iterator, "OpenTTD {}\n", _openttd_revision);
161 str +=
162 "\n"
163 "\n"
164 "Command line options:\n"
165 " -v drv = Set video driver (see below)\n"
166 " -s drv = Set sound driver (see below)\n"
167 " -m drv = Set music driver (see below)\n"
168 " -b drv = Set the blitter to use (see below)\n"
169 " -r res = Set resolution (for instance 800x600)\n"
170 " -h = Display this help text\n"
171 " -t year = Set starting year\n"
172 " -d [[fac=]lvl[,...]]= Debug mode\n"
173 " -e = Start Editor\n"
174 " -g [savegame|scenario|heightmap] = Start new/savegame/scenario/heightmap immediately\n"
175 " -G seed = Set random seed\n"
176 " -n host[:port][#company]= Join network game\n"
177 " -p password = Password to join server\n"
178 " -D [host][:port] = Start dedicated server\n"
179#if !defined(_WIN32)
180 " -f = Fork into the background (dedicated only)\n"
181#endif
182 " -I graphics_set = Force the graphics set (see below)\n"
183 " -S sounds_set = Force the sounds set (see below)\n"
184 " -M music_set = Force the music set (see below)\n"
185 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
186 " -x = Never save configuration changes to disk\n"
187 " -X = Don't use global folders to search for files\n"
188 " -q savegame = Write some information about the savegame and exit\n"
189 " -Q = Don't scan for/load NewGRF files on startup\n"
190 " -QQ = Disable NewGRF scanning/loading entirely\n"
191 "\n";
192
193 /* List the graphics packs */
194 BaseGraphics::GetSetsList(output_iterator);
195
196 /* List the sounds packs */
197 BaseSounds::GetSetsList(output_iterator);
198
199 /* List the music packs */
200 BaseMusic::GetSetsList(output_iterator);
201
202 /* List the drivers */
203 DriverFactoryBase::GetDriversInfo(output_iterator);
204
205 /* List the blitters */
206 BlitterFactory::GetBlittersInfo(output_iterator);
207
208 /* List the debug facilities. */
209 DumpDebugFacilityNames(output_iterator);
210
211 /* We need to initialize the AI, so it finds the AIs */
212 AI::Initialize();
213 AI::GetConsoleList(output_iterator, true);
214 AI::Uninitialize(true);
215
216 /* We need to initialize the GameScript, so it finds the GSs */
217 Game::Initialize();
218 Game::GetConsoleList(output_iterator, true);
219 Game::Uninitialize(true);
220
221 /* ShowInfo put output to stderr, but version information should go
222 * to stdout; this is the only exception */
223#if !defined(_WIN32)
224 fmt::print("{}\n", str);
225#else
226 ShowInfoI(str);
227#endif
228}
229
230static void WriteSavegameInfo(const std::string &name)
231{
232 extern SaveLoadVersion _sl_version;
233 uint32_t last_ottd_rev = 0;
234 uint8_t ever_modified = 0;
235 bool removed_newgrfs = false;
236
237 _gamelog.Info(&last_ottd_rev, &ever_modified, &removed_newgrfs);
238
239 std::string message;
240 message.reserve(1024);
241 format_append(message, "Name: {}\n", name);
242 format_append(message, "Savegame ver: {}\n", _sl_version);
243 format_append(message, "NewGRF ver: 0x{:08X}\n", last_ottd_rev);
244 format_append(message, "Modified: {}\n", ever_modified);
245
246 if (removed_newgrfs) {
247 format_append(message, "NewGRFs have been removed\n");
248 }
249
250 message += "NewGRFs:\n";
251 if (_load_check_data.HasNewGrfs()) {
252 for (const auto &c : _load_check_data.grfconfig) {
253 format_append(message, "{:08X} {} {}\n", std::byteswap(c->ident.grfid),
254 FormatArrayAsHex(c->flags.Test(GRFConfigFlag::Compatible) ? c->original_md5sum : c->ident.md5sum), c->filename);
255 }
256 }
257
258 /* ShowInfo put output to stderr, but version information should go
259 * to stdout; this is the only exception */
260#if !defined(_WIN32)
261 fmt::print("{}\n", message);
262#else
263 ShowInfoI(message);
264#endif
265}
266
267
274 static void ParseResolution(Dimension &res, std::string_view s)
275{
276 StringConsumer consumer(s);
277 auto width = consumer.TryReadIntegerBase<uint>(10);
278 auto valid = consumer.ReadIf("x");
279 auto height = consumer.TryReadIntegerBase<uint>(10);
280 if (!width.has_value() || !valid || !height.has_value() || consumer.AnyBytesLeft()) {
281 ShowInfo("Invalid resolution '{}'", s);
282 return;
283 }
284
285 res.width = std::max<uint>(*width, 64);
286 res.height = std::max<uint>(*height, 64);
287}
288
289
294 static void ShutdownGame()
295{
296 IConsoleFree();
297
298 if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
299
300 SocialIntegration::Shutdown();
301 DriverFactoryBase::ShutdownDrivers();
302
303 UnInitWindowSystem();
304
305 /* stop the scripts */
306 AI::Uninitialize(false);
307 Game::Uninitialize(false);
308
309 /* Uninitialize variables that are allocated dynamically */
310 _gamelog.Reset();
311
312 LinkGraphSchedule::Clear();
313 PoolBase::Clean(PT_ALL);
314
315 /* No NewGRFs were loaded when it was still bootstrapping. */
316 if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
317
318 FontCache::UninitializeFontCaches();
319}
320
325 static void LoadIntroGame(bool load_newgrfs = true)
326{
327 _game_mode = GM_MENU;
328
329 if (load_newgrfs) ResetGRFConfig(false);
330
331 /* Setup main window */
332 ResetWindowSystem();
333 SetupColoursAndInitialWindow();
334
335 /* Load the default opening screen savegame */
336 if (SaveOrLoad("opntitle.dat", SLO_LOAD, DFT_GAME_FILE, BASESET_DIR) != SL_OK) {
337 GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
338 SetLocalCompany(COMPANY_SPECTATOR);
339 } else {
340 SetLocalCompany(CompanyID::Begin());
341 }
342
343 FixTitleGameZoom();
344 _pause_mode = {};
345 _cursor.fix_at = false;
346
347 CheckForMissingGlyphs();
348
349 MusicLoop(); // ensure music is correct
350}
351
352void MakeNewgameSettingsLive()
353{
354 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
355 _settings_game.script_config.ai[c].reset();
356 }
357 _settings_game.script_config.game.reset();
358
359 /* Copy newgame settings to active settings.
360 * Also initialise old settings needed for savegame conversion. */
361 _settings_game = _settings_newgame;
362 _old_vds = _settings_client.company.vehicle;
363}
364
365void OpenBrowser(const std::string &url)
366{
367 /* Make sure we only accept urls that are sure to open a browser. */
368 if (url.starts_with("http://") || url.starts_with("https://")) {
369 OSOpenBrowser(url);
370 }
371}
372
374 struct AfterNewGRFScan : NewGRFScanCallback {
375 TimerGameCalendar::Year startyear = CalendarTime::INVALID_YEAR;
376 uint32_t generation_seed = GENERATE_NEW_SEED;
377 std::string dedicated_host;
378 uint16_t dedicated_port = 0;
379 std::string connection_string;
380 std::string join_server_password;
381 bool save_config = true;
382
386 AfterNewGRFScan()
387 {
388 /* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
389 * if it's placed outside a member function, directly in the struct body. */
390 static_assert(sizeof(generation_seed) == sizeof(_settings_game.game_creation.generation_seed));
391 }
392
393 void OnNewGRFsScanned() override
394 {
395 ResetGRFConfig(false);
396
397 TarScanner::DoScan(TarScanner::Mode::Scenario);
398
399 AI::Initialize();
400 Game::Initialize();
401
402 /* We want the new (correct) NewGRF count to survive the loading. */
403 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
404 LoadFromConfig();
405 _settings_client.gui.last_newgrf_count = last_newgrf_count;
406 /* Since the default for the palette might have changed due to
407 * reading the configuration file, recalculate that now. */
408 UpdateNewGRFConfigPalette();
409
410 Game::Uninitialize(true);
411 AI::Uninitialize(true);
412 LoadFromHighScore();
413 LoadHotkeysFromConfig();
414 WindowDesc::LoadFromConfig();
415
416 /* We have loaded the config, so we may possibly save it. */
417 _save_config = save_config;
418
419 /* restore saved music and effects volumes */
420 MusicDriver::GetInstance()->SetVolume(_settings_client.music.music_vol);
421 SetEffectVolume(_settings_client.music.effect_vol);
422
423 if (startyear != CalendarTime::INVALID_YEAR) IConsoleSetSetting("game_creation.starting_year", startyear.base());
424 _settings_newgame.game_creation.generation_seed = generation_seed;
425
426 if (!dedicated_host.empty()) {
427 _network_bind_list.clear();
428 _network_bind_list.emplace_back(dedicated_host);
429 }
430 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
431
432 /* initialize the ingame console */
433 IConsoleInit();
434 InitializeGUI();
435 IConsoleCmdExec("exec scripts/autoexec.scr 0");
436
437 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
438 if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
439
440 if (_network_available && !connection_string.empty()) {
441 LoadIntroGame();
442 _switch_mode = SM_NONE;
443
444 NetworkClientConnectGame(connection_string, COMPANY_NEW_COMPANY, join_server_password);
445 }
446
447 /* After the scan we're not used anymore. */
448 delete this;
449 }
450};
451
452void PostMainLoop()
453{
454 WaitTillSaved();
455
456 /* only save config if we have to */
457 if (_save_config) {
458 SaveToConfig();
459 SaveHotkeysToConfig();
460 WindowDesc::SaveToConfig();
461 SaveToHighScore();
462 }
463
464 /* Reset windowing system, stop drivers, free used memory, ... */
465 ShutdownGame();
466}
467
468#if defined(UNIX)
469extern void DedicatedFork();
470#endif
471
477 static std::vector<OptionData> CreateOptions()
478{
479 std::vector<OptionData> options;
480 /* Options that require a parameter. */
481 for (char c : "GIMSbcmnpqrstv") options.push_back({ .type = ODF_HAS_VALUE, .id = c, .shortname = c });
482
483 /* Options with an optional parameter. */
484 for (char c : "Ddg") options.push_back({ .type = ODF_OPTIONAL_VALUE, .id = c, .shortname = c });
485
486 /* Options without a parameter. */
487 for (char c : "QXehx") options.push_back({ .type = ODF_NO_VALUE, .id = c, .shortname = c });
488#if !defined(_WIN32)
489 options.push_back({ .type = ODF_NO_VALUE, .id = 'f', .shortname = 'f' });
490#endif
491
492 return options;
493}
494
500 int openttd_main(std::span<std::string_view> arguments)
501{
502 _game_session_stats.start_time = std::chrono::steady_clock::now();
503 _game_session_stats.savegame_size = std::nullopt;
504
505 std::string musicdriver;
506 std::string sounddriver;
507 std::string videodriver;
508 std::string blitter;
509 std::string graphics_set;
510 std::string sounds_set;
511 std::string music_set;
512 Dimension resolution = {0, 0};
513 std::unique_ptr<AfterNewGRFScan> scanner = std::make_unique<AfterNewGRFScan>();
514 bool dedicated = false;
515 bool only_local_path = false;
516
517 extern bool _dedicated_forks;
518 _dedicated_forks = false;
519
520 _game_mode = GM_MENU;
521 _switch_mode = SM_MENU;
522
523 auto options = CreateOptions();
524 GetOptData mgo(arguments.subspan(1), options);
525
526 int i;
527 while ((i = mgo.GetOpt()) != -1) {
528 switch (i) {
529 case 'I': graphics_set = mgo.opt; break;
530 case 'S': sounds_set = mgo.opt; break;
531 case 'M': music_set = mgo.opt; break;
532 case 'm': musicdriver = mgo.opt; break;
533 case 's': sounddriver = mgo.opt; break;
534 case 'v': videodriver = mgo.opt; break;
535 case 'b': blitter = mgo.opt; break;
536 case 'D':
537 musicdriver = "null";
538 sounddriver = "null";
539 videodriver = "dedicated";
540 blitter = "null";
541 dedicated = true;
542 SetDebugString("net=4", ShowInfoI);
543 if (!mgo.opt.empty()) {
544 scanner->dedicated_host = ParseFullConnectionString(mgo.opt, scanner->dedicated_port);
545 }
546 break;
547 case 'f': _dedicated_forks = true; break;
548 case 'n':
549 scanner->connection_string = mgo.opt; // host:port#company parameter
550 break;
551 case 'p':
552 scanner->join_server_password = mgo.opt;
553 break;
554 case 'r': ParseResolution(resolution, mgo.opt); break;
555 case 't':
556 if (auto value = ParseInteger(mgo.opt); value.has_value()) {
557 scanner->startyear = TimerGameCalendar::Year(*value);
558 } else {
559 fmt::print(stderr, "Invalid start year: {}\n", mgo.opt);
560 }
561 break;
562 case 'd': {
563#if defined(_WIN32)
564 CreateConsole();
565#endif
566 if (!mgo.opt.empty()) SetDebugString(mgo.opt, ShowInfoI);
567 break;
568 }
569 case 'e':
570 /* Allow for '-e' before or after '-g'. */
571 switch (_switch_mode) {
572 case SM_MENU: _switch_mode = SM_EDITOR; break;
573 case SM_LOAD_GAME: _switch_mode = SM_LOAD_SCENARIO; break;
574 case SM_START_HEIGHTMAP: _switch_mode = SM_LOAD_HEIGHTMAP; break;
575 default: break;
576 }
577 break;
578 case 'g':
579 if (!mgo.opt.empty()) {
580 _file_to_saveload.name = mgo.opt;
581
582 std::string extension = FS2OTTD(std::filesystem::path(OTTD2FS(_file_to_saveload.name)).extension().native());
583 auto [ft, _] = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, extension);
584 if (ft == FIOS_TYPE_INVALID) {
585 std::tie(ft, _) = FiosGetScenarioListCallback(SLO_LOAD, _file_to_saveload.name, extension);
586 }
587 if (ft == FIOS_TYPE_INVALID) {
588 std::tie(ft, _) = FiosGetHeightmapListCallback(SLO_LOAD, _file_to_saveload.name, extension);
589 }
590
591 /* Allow for '-e' before or after '-g'. */
592 switch (ft.abstract) {
593 case FT_SAVEGAME: _switch_mode = (_switch_mode == SM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME); break;
594 case FT_SCENARIO: _switch_mode = (_switch_mode == SM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME); break;
595 case FT_HEIGHTMAP: _switch_mode = (_switch_mode == SM_EDITOR ? SM_LOAD_HEIGHTMAP : SM_START_HEIGHTMAP); break;
596 default: break;
597 }
598
599 _file_to_saveload.SetMode(ft, SLO_LOAD);
600 break;
601 }
602
603 _switch_mode = SM_NEWGAME;
604 /* Give a random map if no seed has been given */
605 if (scanner->generation_seed == GENERATE_NEW_SEED) {
606 scanner->generation_seed = InteractiveRandom();
607 }
608 break;
609 case 'q': {
610 DeterminePaths(arguments[0], only_local_path);
611 if (mgo.opt.empty()) {
612 return 1;
613 }
614
615 std::string extension = FS2OTTD(std::filesystem::path(OTTD2FS(mgo.opt)).extension().native());
616 auto [_, title] = FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, extension);
617
618 _load_check_data.Clear();
619 SaveOrLoadResult res = SaveOrLoad(mgo.opt, SLO_CHECK, DFT_GAME_FILE, SAVE_DIR, false);
620 if (res != SL_OK || _load_check_data.HasErrors()) {
621 fmt::print(stderr, "Failed to open savegame\n");
622 if (_load_check_data.HasErrors()) {
623 InitializeLanguagePacks(); // A language pack is needed for GetString()
624 fmt::print(stderr, "{}\n", GetString(_load_check_data.error, _load_check_data.error_msg));
625 }
626 return 1;
627 }
628
629 WriteSavegameInfo(title);
630 return 0;
631 }
632 case 'Q': {
633 extern int _skip_all_newgrf_scanning;
634 _skip_all_newgrf_scanning += 1;
635 break;
636 }
637 case 'G':
638 if (auto value = ParseInteger(mgo.opt); value.has_value()) {
639 scanner->generation_seed = *value;
640 } else {
641 fmt::print(stderr, "Invalid generation seed: {}\n", mgo.opt);
642 }
643 break;
644 case 'c': _config_file = mgo.opt; break;
645 case 'x': scanner->save_config = false; break;
646 case 'X': only_local_path = true; break;
647 case 'h': break; // handled below
648 }
649 if (i == 'h' || i == -2) break;
650 }
651
652 if (i == 'h' || i == -2 || !mgo.arguments.empty()) {
653 /* Either the user typed '-h', they made an error, or they added unrecognized command line arguments.
654 * In all cases, print the help, and exit.
655 *
656 * The next two functions are needed to list the graphics sets. We can't do them earlier
657 * because then we cannot show it on the debug console as that hasn't been configured yet. */
658 DeterminePaths(arguments[0], only_local_path);
659 TarScanner::DoScan(TarScanner::Mode::Baseset);
660 BaseGraphics::FindSets();
661 BaseSounds::FindSets();
662 BaseMusic::FindSets();
663 ShowHelp();
664
665 /* Return zero when asked to print help, and 1 for all other cases. */
666 if (i == 'h') return 0;
667 return 1;
668 }
669
670 DeterminePaths(arguments[0], only_local_path);
671 TarScanner::DoScan(TarScanner::Mode::Baseset);
672
673 if (dedicated) Debug(net, 3, "Starting dedicated server, version {}", _openttd_revision);
674 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
675
676#if defined(UNIX)
677 /* We must fork here, or we'll end up without some resources we need (like sockets) */
678 if (_dedicated_forks) DedicatedFork();
679#endif
680
681 LoadFromConfig(true);
682
683 if (resolution.width != 0) _cur_resolution = resolution;
684
685 /* Limit width times height times bytes per pixel to fit a 32 bit
686 * integer, This way all internal drawing routines work correctly.
687 * A resolution that has one component as 0 is treated as a marker to
688 * auto-detect a good window size. */
689 _cur_resolution.width = std::min(_cur_resolution.width, UINT16_MAX / 2u);
690 _cur_resolution.height = std::min(_cur_resolution.height, UINT16_MAX / 2u);
691
692 /* Assume the cursor starts within the game as not all video drivers
693 * get an event that the cursor is within the window when it is opened.
694 * Saying the cursor is there makes no visible difference as it would
695 * just be out of the bounds of the window. */
696 _cursor.in_window = true;
697
698 /* enumerate language files */
699 InitializeLanguagePacks();
700
701 /* Initialize the font cache */
702 FontCache::LoadFontCaches(FONTSIZES_REQUIRED);
703
704 /* This must be done early, since functions use the SetWindowDirty* calls */
705 InitWindowSystem();
706
707 BaseGraphics::FindSets();
708 bool valid_graphics_set;
709 if (!graphics_set.empty()) {
710 valid_graphics_set = BaseGraphics::SetSetByName(graphics_set);
711 } else if (BaseGraphics::ini_data.shortname != 0) {
712 graphics_set = BaseGraphics::ini_data.name;
713 valid_graphics_set = BaseGraphics::SetSetByShortname(BaseGraphics::ini_data.shortname);
714 if (valid_graphics_set && !BaseGraphics::ini_data.extra_params.empty()) {
715 GRFConfig &extra_cfg = BaseGraphics::GetUsedSet()->GetOrCreateExtraConfig();
716 if (extra_cfg.IsCompatible(BaseGraphics::ini_data.extra_version)) {
717 extra_cfg.SetParams(BaseGraphics::ini_data.extra_params);
718 }
719 }
720 } else if (!BaseGraphics::ini_data.name.empty()) {
721 graphics_set = BaseGraphics::ini_data.name;
722 valid_graphics_set = BaseGraphics::SetSetByName(BaseGraphics::ini_data.name);
723 } else {
724 valid_graphics_set = true;
725 BaseGraphics::SetSet(nullptr); // ignore error, continue to bootstrap GUI
726 }
727 if (!valid_graphics_set) {
728 BaseGraphics::SetSet(nullptr);
729
730 ErrorMessageData msg(GetEncodedString(STR_CONFIG_ERROR), GetEncodedString(STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND, graphics_set));
731 ScheduleErrorMessage(msg);
732 }
733
734 /* Initialize game palette */
735 GfxInitPalettes();
736
737 Debug(misc, 1, "Loading blitter...");
738 if (blitter.empty() && !_ini_blitter.empty()) blitter = _ini_blitter;
739 _blitter_autodetected = blitter.empty();
740 /* Activate the initial blitter.
741 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
742 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
743 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
744 * - Use 8bpp blitter otherwise.
745 */
746 if (!_blitter_autodetected ||
747 (_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
748 BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
749 if (BlitterFactory::SelectBlitter(blitter) == nullptr) {
750 blitter.empty() ?
751 UserError("Failed to autoprobe blitter") :
752 UserError("Failed to select requested blitter '{}'; does it exist?", blitter);
753 }
754 }
755
756 if (videodriver.empty() && !_ini_videodriver.empty()) videodriver = _ini_videodriver;
757 DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
758
759 InitializeSpriteSorter();
760
761 /* Initialize the zoom level of the screen to normal */
762 _screen.zoom = ZoomLevel::Min;
763
764 /* The video driver is now selected, now initialise GUI zoom */
765 UpdateGUIZoom();
766
767 SocialIntegration::Initialize();
768 NetworkStartUp(); // initialize network-core
769
770 if (!HandleBootstrap()) {
771 ShutdownGame();
772 return 0;
773 }
774
775 VideoDriver::GetInstance()->ClaimMousePointer();
776
777 BaseSounds::FindSets();
778 if (sounds_set.empty() && !BaseSounds::ini_set.empty()) sounds_set = BaseSounds::ini_set;
779 if (!BaseSounds::SetSetByName(sounds_set)) {
780 if (sounds_set.empty() || !BaseSounds::SetSet({})) {
781 UserError("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
782 } else {
783 ErrorMessageData msg(GetEncodedString(STR_CONFIG_ERROR), GetEncodedString(STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND, sounds_set));
784 ScheduleErrorMessage(msg);
785 }
786 }
787
788 BaseMusic::FindSets();
789 if (music_set.empty() && !BaseMusic::ini_set.empty()) music_set = BaseMusic::ini_set;
790 if (!BaseMusic::SetSetByName(music_set)) {
791 if (music_set.empty() || !BaseMusic::SetSet({})) {
792 UserError("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
793 } else {
794 ErrorMessageData msg(GetEncodedString(STR_CONFIG_ERROR), GetEncodedString(STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND, music_set));
795 ScheduleErrorMessage(msg);
796 }
797 }
798
799 if (sounddriver.empty() && !_ini_sounddriver.empty()) sounddriver = _ini_sounddriver;
800 DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
801
802 if (musicdriver.empty() && !_ini_musicdriver.empty()) musicdriver = _ini_musicdriver;
803 DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
804
805 GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
806 LoadIntroGame(false);
807
808 /* ScanNewGRFFiles now has control over the scanner. */
809 RequestNewGRFScan(scanner.release());
810
811 VideoDriver::GetInstance()->MainLoop();
812
813 PostMainLoop();
814 return 0;
815}
816
817void HandleExitGameRequest()
818{
819 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
820 _exit_game = true;
821 } else if (_settings_client.gui.autosave_on_exit) {
822 DoExitSave();
823 _survey.Transmit(NetworkSurveyHandler::Reason::EXIT, true);
824 _exit_game = true;
825 } else {
826 AskExitGame();
827 }
828}
829
833 static void OnStartScenario()
834{
835 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
836 EngineOverrideManager::ResetToCurrentNewGRFConfig();
837
838 /* Make sure all industries were built "this year", to avoid too early closures. (#9918) */
839 for (Industry *i : Industry::Iterate()) {
840 i->last_prod_year = TimerGameEconomy::year;
841 }
842}
843
848 static void OnStartGame(bool dedicated_server)
849{
850 /* Update the local company for a loaded game. It is either the first available company
851 * or in the case of a dedicated server, a spectator */
852 SetLocalCompany(dedicated_server ? COMPANY_SPECTATOR : GetFirstPlayableCompanyID());
853
854 NetworkOnGameStart();
855
856 /* Execute the game-start script */
857 IConsoleCmdExec("exec scripts/game_start.scr 0");
858}
859
860static void MakeNewGameDone()
861{
862 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
863
864 /* In a dedicated server, the server does not play */
865 if (!VideoDriver::GetInstance()->HasGUI()) {
866 OnStartGame(true);
867 if (_settings_client.gui.pause_on_newgame) Command<CMD_PAUSE>::Post(PauseMode::Normal, true);
868 return;
869 }
870
871 /* Create a single company */
872 DoStartupNewCompany(false);
873
874 Company *c = Company::Get(CompanyID::Begin());
875 c->settings = _settings_client.company;
876
877 /* Overwrite colour from settings if needed
878 * COLOUR_END corresponds to Random colour */
879
880 if (_settings_client.gui.starting_colour != COLOUR_END) {
881 Command<CMD_SET_COMPANY_COLOUR>::Post(LS_DEFAULT, true, _settings_client.gui.starting_colour);
882 }
883
884 if (_settings_client.gui.starting_colour_secondary != COLOUR_END && HasBit(_loaded_newgrf_features.used_liveries, LS_DEFAULT)) {
885 Command<CMD_SET_COMPANY_COLOUR>::Post(LS_DEFAULT, false, _settings_client.gui.starting_colour_secondary);
886 }
887
888 OnStartGame(false);
889
890 InitializeRailGUI();
891 InitializeRoadGUI();
892
893 if (_settings_client.gui.pause_on_newgame) Command<CMD_PAUSE>::Post(PauseMode::Normal, true);
894
895 CheckEngines();
896 CheckIndustries();
897 MarkWholeScreenDirty();
898}
899
900static void MakeNewGame(bool from_heightmap, bool reset_settings)
901{
902 _game_mode = GM_NORMAL;
903 if (!from_heightmap) {
904 /* "reload" command needs to know what mode we were in. */
905 _file_to_saveload.SetMode(FIOS_TYPE_INVALID, SLO_INVALID);
906 }
907
908 ResetGRFConfig(true);
909
910 GenerateWorldSetCallback(&MakeNewGameDone);
911 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
912}
913
914static void MakeNewEditorWorldDone()
915{
916 SetLocalCompany(OWNER_NONE);
917}
918
919static void MakeNewEditorWorld()
920{
921 _game_mode = GM_EDITOR;
922 /* "reload" command needs to know what mode we were in. */
923 _file_to_saveload.SetMode(FIOS_TYPE_INVALID, SLO_INVALID);
924
925 ResetGRFConfig(true);
926
927 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
928 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
929}
930
941 bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, std::shared_ptr<LoadFilter> lf = nullptr)
942{
943 assert(fop == SLO_LOAD);
944 assert(dft == DFT_GAME_FILE || (lf == nullptr && dft == DFT_OLD_GAME_FILE));
945 GameMode ogm = _game_mode;
946
947 _game_mode = newgm;
948
949 SaveOrLoadResult result = (lf == nullptr) ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(std::move(lf));
950 if (result == SL_OK) return true;
951
952 if (_network_dedicated && ogm == GM_MENU) {
953 /*
954 * If we are a dedicated server *and* we just were in the menu, then we
955 * are loading the first savegame. If that fails, not starting the
956 * server is a better reaction than starting the server with a newly
957 * generated map as it is quite likely to be started from a script.
958 */
959 Debug(net, 0, "Loading requested map failed; closing server.");
960 _exit_game = true;
961 return false;
962 }
963
964 if (result != SL_REINIT) {
965 _game_mode = ogm;
966 return false;
967 }
968
969 if (_network_dedicated) {
970 /*
971 * If we are a dedicated server, have already loaded/started a game,
972 * and then loading the savegame fails in a manner that we need to
973 * reinitialize everything. We must not fall back into the menu mode
974 * with the intro game, as that is unjoinable by clients. So there is
975 * nothing else to do than start a new game, as it might have failed
976 * trying to reload the originally loaded savegame/scenario.
977 */
978 Debug(net, 0, "Loading game failed, so a new (random) game will be started");
979 MakeNewGame(false, true);
980 return false;
981 }
982
983 if (_network_server) {
984 /* We can't load the intro game as server, so disconnect first. */
985 NetworkDisconnect();
986 }
987
988 switch (ogm) {
989 default:
990 case GM_MENU: LoadIntroGame(); break;
991 case GM_EDITOR: MakeNewEditorWorld(); break;
992 }
993 return false;
994}
995
996static void UpdateSocialIntegration(GameMode game_mode)
997{
998 switch (game_mode) {
999 case GM_BOOTSTRAP:
1000 case GM_MENU:
1001 SocialIntegration::EventEnterMainMenu();
1002 break;
1003
1004 case GM_NORMAL:
1005 if (_networking) {
1006 SocialIntegration::EventEnterMultiplayer(Map::SizeX(), Map::SizeY());
1007 } else {
1008 SocialIntegration::EventEnterSingleplayer(Map::SizeX(), Map::SizeY());
1009 }
1010 break;
1011
1012 case GM_EDITOR:
1013 SocialIntegration::EventEnterScenarioEditor(Map::SizeX(), Map::SizeY());
1014 break;
1015 }
1016}
1017
1018void SwitchToMode(SwitchMode new_mode)
1019{
1020 /* If we are saving something, the network stays in its current state */
1021 if (new_mode != SM_SAVE_GAME) {
1022 /* If the network is active, make it not-active */
1023 if (_networking) {
1024 if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
1025 NetworkReboot();
1026 } else {
1027 NetworkDisconnect();
1028 }
1029 }
1030
1031 /* If we are a server, we restart the server */
1032 if (_is_network_server) {
1033 /* But not if we are going to the menu */
1034 if (new_mode != SM_MENU) {
1035 /* check if we should reload the config */
1036 if (_settings_client.network.reload_cfg) {
1037 LoadFromConfig();
1038 MakeNewgameSettingsLive();
1039 ResetGRFConfig(false);
1040 }
1041 NetworkServerStart();
1042 } else {
1043 /* This client no longer wants to be a network-server */
1044 _is_network_server = false;
1045 }
1046 }
1047 }
1048
1049 /* Make sure all AI controllers are gone at quitting game */
1050 if (new_mode != SM_SAVE_GAME) AI::KillAll();
1051
1052 /* When we change mode, reset the autosave. */
1053 if (new_mode != SM_SAVE_GAME) ChangeAutosaveFrequency(true);
1054
1055 /* Transmit the survey if we were in normal-mode and not saving. It always means we leaving the current game. */
1056 if (_game_mode == GM_NORMAL && new_mode != SM_SAVE_GAME) _survey.Transmit(NetworkSurveyHandler::Reason::LEAVE);
1057
1058 /* Keep track when we last switch mode. Used for survey, to know how long someone was in a game. */
1059 if (new_mode != SM_SAVE_GAME) {
1060 _game_session_stats.start_time = std::chrono::steady_clock::now();
1061 _game_session_stats.savegame_size = std::nullopt;
1062 }
1063
1064 switch (new_mode) {
1065 case SM_EDITOR: // Switch to scenario editor
1066 MakeNewEditorWorld();
1067 GenerateSavegameId();
1068
1069 UpdateSocialIntegration(GM_EDITOR);
1070 break;
1071
1072 case SM_RELOADGAME: // Reload with what-ever started the game
1073 if (_file_to_saveload.ftype.abstract == FT_SAVEGAME || _file_to_saveload.ftype.abstract == FT_SCENARIO) {
1074 /* Reload current savegame/scenario */
1075 _switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
1076 SwitchToMode(_switch_mode);
1077 break;
1078 } else if (_file_to_saveload.ftype.abstract == FT_HEIGHTMAP) {
1079 /* Restart current heightmap */
1080 _switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_HEIGHTMAP : SM_RESTART_HEIGHTMAP;
1081 SwitchToMode(_switch_mode);
1082 break;
1083 }
1084
1085 MakeNewGame(false, new_mode == SM_NEWGAME);
1086 GenerateSavegameId();
1087
1088 UpdateSocialIntegration(GM_NORMAL);
1089 break;
1090
1091 case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1092 case SM_NEWGAME: // New Game --> 'Random game'
1093 MakeNewGame(false, new_mode == SM_NEWGAME);
1094 GenerateSavegameId();
1095
1096 UpdateSocialIntegration(GM_NORMAL);
1097 break;
1098
1099 case SM_LOAD_GAME: { // Load game, Play Scenario
1100 ResetGRFConfig(true);
1101 ResetWindowSystem();
1102
1103 if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.ftype.detailed, GM_NORMAL, NO_DIRECTORY)) {
1104 ShowErrorMessage(GetSaveLoadErrorType(), GetSaveLoadErrorMessage(), WL_CRITICAL);
1105 } else {
1106 if (_file_to_saveload.ftype.abstract == FT_SCENARIO) {
1107 OnStartScenario();
1108 }
1109 OnStartGame(_network_dedicated);
1110 /* Decrease pause counter (was increased from opening load dialog) */
1111 Command<CMD_PAUSE>::Post(PauseMode::SaveLoad, false);
1112 }
1113
1114 UpdateSocialIntegration(GM_NORMAL);
1115 break;
1116 }
1117
1118 case SM_RESTART_HEIGHTMAP: // Load a heightmap and start a new game from it with current settings
1119 case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1120 MakeNewGame(true, new_mode == SM_START_HEIGHTMAP);
1121 GenerateSavegameId();
1122
1123 UpdateSocialIntegration(GM_NORMAL);
1124 break;
1125
1126 case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1127 SetLocalCompany(OWNER_NONE);
1128
1129 _game_mode = GM_EDITOR;
1130
1131 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1132 GenerateSavegameId();
1133 MarkWholeScreenDirty();
1134
1135 UpdateSocialIntegration(GM_EDITOR);
1136 break;
1137
1138 case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1139 if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.ftype.detailed, GM_EDITOR, NO_DIRECTORY)) {
1140 SetLocalCompany(OWNER_NONE);
1141 GenerateSavegameId();
1142 _settings_newgame.game_creation.starting_year = TimerGameCalendar::year;
1143 /* Cancel the saveload pausing */
1144 Command<CMD_PAUSE>::Post(PauseMode::SaveLoad, false);
1145 } else {
1146 ShowErrorMessage(GetSaveLoadErrorType(), GetSaveLoadErrorMessage(), WL_CRITICAL);
1147 }
1148
1149 UpdateSocialIntegration(GM_EDITOR);
1150 break;
1151 }
1152
1153 case SM_JOIN_GAME: // Join a multiplayer game
1154 LoadIntroGame();
1155 NetworkClientJoinGame();
1156
1157 SocialIntegration::EventJoiningMultiplayer();
1158 break;
1159
1160 case SM_MENU: // Switch to game intro menu
1161 LoadIntroGame();
1162 if (BaseSounds::ini_set.empty() && BaseSounds::GetUsedSet()->fallback && SoundDriver::GetInstance()->HasOutput()) {
1163 ShowErrorMessage(GetEncodedString(STR_WARNING_FALLBACK_SOUNDSET), {}, WL_CRITICAL);
1164 BaseSounds::ini_set = BaseSounds::GetUsedSet()->name;
1165 }
1166 if (_settings_client.network.participate_survey == PS_ASK) {
1167 /* No matter how often you go back to the main menu, only ask the first time. */
1168 static bool asked_once = false;
1169 if (!asked_once) {
1170 asked_once = true;
1171 ShowNetworkAskSurvey();
1172 }
1173 }
1174
1175 UpdateSocialIntegration(GM_MENU);
1176 break;
1177
1178 case SM_SAVE_GAME: // Save game.
1179 /* Make network saved games on pause compatible to singleplayer mode */
1180 if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
1181 ShowErrorMessage(GetSaveLoadErrorType(), GetSaveLoadErrorMessage(), WL_ERROR);
1182 } else {
1183 CloseWindowById(WC_SAVELOAD, 0);
1184 }
1185 break;
1186
1187 case SM_SAVE_HEIGHTMAP: // Save heightmap.
1188 MakeHeightmapScreenshot(_file_to_saveload.name);
1189 CloseWindowById(WC_SAVELOAD, 0);
1190 break;
1191
1192 case SM_GENRANDLAND: // Generate random land within scenario editor
1193 SetLocalCompany(OWNER_NONE);
1194 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1195 /* XXX: set date */
1196 MarkWholeScreenDirty();
1197 break;
1198
1199 default: NOT_REACHED();
1200 }
1201}
1202
1203
1204
1210 void StateGameLoop()
1211{
1212 if (!_networking || _network_server) {
1213 StateGameLoop_LinkGraphPauseControl();
1214 }
1215
1216 /* Don't execute the state loop during pause or when modal windows are open. */
1217 if (_pause_mode.Any() || HasModalProgress()) {
1218 PerformanceMeasurer::Paused(PFE_GAMELOOP);
1219 PerformanceMeasurer::Paused(PFE_GL_ECONOMY);
1220 PerformanceMeasurer::Paused(PFE_GL_TRAINS);
1221 PerformanceMeasurer::Paused(PFE_GL_ROADVEHS);
1222 PerformanceMeasurer::Paused(PFE_GL_SHIPS);
1223 PerformanceMeasurer::Paused(PFE_GL_AIRCRAFT);
1224 PerformanceMeasurer::Paused(PFE_GL_LANDSCAPE);
1225
1226 if (!HasModalProgress()) UpdateLandscapingLimits();
1227#ifndef DEBUG_DUMP_COMMANDS
1228 if (_game_mode == GM_NORMAL) Game::GameLoop();
1229#endif
1230 return;
1231 }
1232
1233 PerformanceMeasurer framerate(PFE_GAMELOOP);
1234 PerformanceAccumulator::Reset(PFE_GL_LANDSCAPE);
1235
1236 if (_game_mode == GM_EDITOR) {
1237 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1238 RunTileLoop();
1239 CallVehicleTicks();
1240 CallLandscapeTick();
1241 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1242 UpdateLandscapingLimits();
1243
1244 CallWindowGameTickEvent();
1245 NewsLoop();
1246 } else {
1247 if (_debug_desync_level > 2 && TimerGameEconomy::date_fract == 0 && (TimerGameEconomy::date.base() & 0x1F) == 0) {
1248 /* Save the desync savegame if needed. */
1249 std::string name = fmt::format("dmp_cmds_{:08x}_{:08x}.sav", _settings_game.game_creation.generation_seed, TimerGameEconomy::date);
1250 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
1251 }
1252
1253 CheckCaches();
1254
1255 /* All these actions has to be done from OWNER_NONE
1256 * for multiplayer compatibility */
1257 Backup<CompanyID> cur_company(_current_company, OWNER_NONE);
1258
1259 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1260 AnimateAnimatedTiles();
1261 if (TimerManager<TimerGameCalendar>::Elapsed(1)) {
1262 RunVehicleCalendarDayProc();
1263 }
1264 TimerManager<TimerGameEconomy>::Elapsed(1);
1265 TimerManager<TimerGameTick>::Elapsed(1);
1266 RunTileLoop();
1267 CallVehicleTicks();
1268 CallLandscapeTick();
1269 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1270
1271#ifndef DEBUG_DUMP_COMMANDS
1272 {
1273 PerformanceMeasurer script_framerate(PFE_ALLSCRIPTS);
1274 AI::GameLoop();
1275 Game::GameLoop();
1276 }
1277#endif
1278 UpdateLandscapingLimits();
1279
1280 CallWindowGameTickEvent();
1281 NewsLoop();
1282 cur_company.Restore();
1283 }
1284
1285 assert(IsLocalCompany());
1286}
1287
1289 static IntervalTimer<TimerGameRealtime> _autosave_interval({std::chrono::milliseconds::zero(), TimerGameRealtime::AUTOSAVE}, [](auto)
1290{
1291 /* We reset the command-during-pause mode here, so we don't continue
1292 * to make auto-saves when nothing more is changing. */
1293 _pause_mode.Reset(PauseMode::CommandDuringPause);
1294
1295 _do_autosave = true;
1296 SetWindowDirty(WC_STATUS_BAR, 0);
1297
1298 static FiosNumberedSaveName _autosave_ctr("autosave");
1299 DoAutoOrNetsave(_autosave_ctr);
1300
1301 _do_autosave = false;
1302 SetWindowDirty(WC_STATUS_BAR, 0);
1303});
1304
1314 void ChangeAutosaveFrequency(bool reset)
1315{
1316 _autosave_interval.SetInterval({std::chrono::minutes(_settings_client.gui.autosave_interval), TimerGameRealtime::AUTOSAVE}, reset);
1317}
1318
1327 bool RequestNewGRFScan(NewGRFScanCallback *callback)
1328{
1329 if (_request_newgrf_scan) return false;
1330
1331 _request_newgrf_scan = true;
1332 _request_newgrf_scan_callback = callback;
1333 return true;
1334}
1335
1336void GameLoop()
1337{
1338 if (_game_mode == GM_BOOTSTRAP) {
1339 /* Check for UDP stuff */
1340 if (_network_available) NetworkBackgroundLoop();
1341 return;
1342 }
1343
1344 if (_request_newgrf_scan) {
1345 ScanNewGRFFiles(_request_newgrf_scan_callback);
1346 _request_newgrf_scan = false;
1347 _request_newgrf_scan_callback = nullptr;
1348 /* In case someone closed the game during our scan, don't do anything else. */
1349 if (_exit_game) return;
1350 }
1351
1352 ProcessAsyncSaveFinish();
1353
1354 if (_game_mode == GM_NORMAL) {
1355 static auto last_time = std::chrono::steady_clock::now();
1356 auto now = std::chrono::steady_clock::now();
1357 auto delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_time);
1358 if (delta_ms.count() != 0) {
1359 TimerManager<TimerGameRealtime>::Elapsed(delta_ms);
1360 last_time = now;
1361 }
1362 }
1363
1364 /* switch game mode? */
1365 if (_switch_mode != SM_NONE && !HasModalProgress()) {
1366 SwitchToMode(_switch_mode);
1367 _switch_mode = SM_NONE;
1368 if (_exit_game) return;
1369 }
1370
1371 IncreaseSpriteLRU();
1372
1373 /* Check for UDP stuff */
1374 if (_network_available) NetworkBackgroundLoop();
1375
1376 DebugSendRemoteMessages();
1377
1378 if (_networking && !HasModalProgress()) {
1379 /* Multiplayer */
1380 NetworkGameLoop();
1381 } else {
1382 if (_network_reconnect > 0 && --_network_reconnect == 0) {
1383 /* This means that we want to reconnect to the last host
1384 * We do this here, because it means that the network is really closed */
1385 NetworkClientConnectGame(_settings_client.network.last_joined, COMPANY_SPECTATOR);
1386 }
1387 /* Singleplayer */
1388 StateGameLoop();
1389 }
1390
1391 if (_pause_mode.None() && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1392
1393 SoundDriver::GetInstance()->MainLoop();
1394 MusicLoop();
1395 SocialIntegration::RunCallbacks();
1396}
ai.hpp
Base functions for all AIs.
ai_config.hpp
AIConfig stores the configuration settings of every AI.
aircraft.h
Base for aircraft.
AnimateAnimatedTiles
void AnimateAnimatedTiles()
Animate all tiles in the animated tile list, i.e. call AnimateTile on them.
Definition animated_tile.cpp:75
animated_tile_func.h
Tile animation!
backup_type.hpp
Class for backupping variables and making sure they are restored later.
base_media_base.h
Generic functions for replacing base data (graphics, sounds).
base_media_graphics.h
Generic functions for replacing base graphics data.
BLT_8BPP
@ BLT_8BPP
Base set has 8 bpp sprites only.
Definition base_media_graphics.h:28
base_media_music.h
Generic functions for replacing base music data.
base_media_sounds.h
Generic functions for replacing base sounds data.
HasBit
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition bitmath_func.hpp:103
AI::Uninitialize
static void Uninitialize(bool keepConfig)
Uninitialize the AI system.
Definition ai_core.cpp:179
AI::Initialize
static void Initialize()
Initialize the AI system.
Definition ai_core.cpp:165
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:288
AI::GameLoop
static void GameLoop()
Called every game-tick to let AIs do something.
Definition ai_core.cpp:74
AI::KillAll
static void KillAll()
Kill any and all AIs we manage.
Definition ai_core.cpp:155
BaseBitSet::None
constexpr bool None() const
Test if none of the values are set.
Definition base_bitset_type.hpp:188
BaseBitSet::Reset
constexpr Timpl & Reset()
Reset all bits.
Definition base_bitset_type.hpp:83
BaseBitSet::Any
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Definition base_bitset_type.hpp:170
BaseMedia< GraphicsSet >::GetUsedSet
static const GraphicsSet * GetUsedSet()
Return the used set.
Definition base_media_func.h:400
BaseMedia< GraphicsSet >::SetSetByShortname
static bool SetSetByShortname(uint32_t shortname)
Set the set to be used.
Definition base_media_func.h:287
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:306
BaseMedia< GraphicsSet >::FindSets
static uint FindSets()
Do the scan for files.
Definition base_media_base.h:191
BaseMedia< GraphicsSet >::SetSetByName
static bool SetSetByName(const std::string &name)
Set the set to be used.
Definition base_media_func.h:267
BaseMedia< GraphicsSet >::SetSet
static bool SetSet(const GraphicsSet *set)
Set the set to be used.
Definition base_media_func.h:250
BaseMusic::ini_set
static std::string ini_set
The set as saved in the config file.
Definition base_media_music.h:66
BaseSounds::ini_set
static std::string ini_set
The set as saved in the config file.
Definition base_media_sounds.h:28
BlitterFactory::GetBlittersInfo
static void GetBlittersInfo(std::back_insert_iterator< std::string > &output_iterator)
Fill a buffer with information about the blitters.
Definition factory.hpp:147
BlitterFactory::SelectBlitter
static Blitter * SelectBlitter(std::string_view name)
Find the requested blitter and return its class.
Definition factory.hpp:96
CrashLog::SetErrorMessage
static void SetErrorMessage(const std::string &message)
Sets a message for the error message handler.
Definition crashlog.cpp:329
DriverFactoryBase::ShutdownDrivers
static void ShutdownDrivers()
Shuts down all active drivers.
Definition driver.h:123
DriverFactoryBase::SelectDriver
static void SelectDriver(const std::string &name, Driver::Type type)
Find the requested driver and return its class.
Definition driver.cpp:94
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:221
Driver::Stop
virtual void Stop()=0
Stop this driver.
Driver::DT_VIDEO
@ DT_VIDEO
A video driver.
Definition driver.h:42
Driver::DT_SOUND
@ DT_SOUND
A sound driver.
Definition driver.h:41
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
ErrorMessageData
The data of the error message.
Definition error.h:31
FontCache::UninitializeFontCaches
static void UninitializeFontCaches()
Free everything allocated w.r.t.
Definition fontcache.cpp:267
FontCache::LoadFontCaches
static void LoadFontCaches(FontSizes fontsizes)
(Re)initialize the font cache related things, i.e.
Definition fontcache.cpp:237
Game::GameLoop
static void GameLoop()
Called every game-tick to let Game do something.
Definition game_core.cpp:31
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:203
Game::Uninitialize
static void Uninitialize(bool keepConfig)
Uninitialize the Game system.
Definition game_core.cpp:102
Game::Initialize
static void Initialize()
Initialize the Game system.
Definition game_core.cpp:57
Gamelog::Info
void Info(uint32_t *last_ottd_rev, uint8_t *ever_modified, bool *removed_newgrfs)
Get some basic information from the given gamelog.
Definition gamelog.cpp:685
Gamelog::Reset
void Reset()
Resets and frees all memory allocated - used before loading or starting a new game.
Definition gamelog.cpp:94
IntervalTimer
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
IntervalTimer::SetInterval
void SetInterval(const TPeriod interval, bool reset=true)
Set a new interval for the timer.
Definition timer.h:99
LinkGraphSchedule::Clear
static void Clear()
Clear all link graphs and jobs from the schedule.
Definition linkgraphschedule.cpp:121
MusicDriver::GetInstance
static MusicDriver * GetInstance()
Get the currently active instance of the music driver.
Definition music_driver.hpp:46
MusicDriver::SetVolume
virtual void SetVolume(uint8_t vol)=0
Set the volume, if possible.
NetworkSurveyHandler::Reason::EXIT
@ EXIT
User is exiting the application.
NetworkSurveyHandler::Reason::LEAVE
@ LEAVE
User is leaving the game (but not exiting the application).
NetworkSurveyHandler::Transmit
void Transmit(Reason reason, bool blocking=false)
Transmit the survey.
Definition network_survey.cpp:86
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:332
PerformanceMeasurer
RAII class for measuring simple elements of performance.
Definition framerate_type.h:91
PerformanceMeasurer::Paused
static void Paused(PerformanceElement elem)
Indicate that a cycle of "pause" where no processing occurs.
Definition framerate_gui.cpp:302
SocialIntegration::EventEnterScenarioEditor
static void EventEnterScenarioEditor(uint map_width, uint map_height)
Event: user entered the Scenario Editor.
Definition social_integration.cpp:220
SocialIntegration::EventEnterSingleplayer
static void EventEnterSingleplayer(uint map_width, uint map_height)
Event: user entered a singleplayer game.
Definition social_integration.cpp:227
SocialIntegration::RunCallbacks
static void RunCallbacks()
Allow any social integration library to handle their own events.
Definition social_integration.cpp:194
SocialIntegration::EventEnterMultiplayer
static void EventEnterMultiplayer(uint map_width, uint map_height)
Event: user entered a multiplayer game.
Definition social_integration.cpp:234
SocialIntegration::Shutdown
static void Shutdown()
Shutdown the social integration system, and all social integration plugins that are loaded.
Definition social_integration.cpp:184
SocialIntegration::EventEnterMainMenu
static void EventEnterMainMenu()
Event: user entered the main menu.
Definition social_integration.cpp:213
SocialIntegration::EventJoiningMultiplayer
static void EventJoiningMultiplayer()
Event: user is joining a multiplayer game.
Definition social_integration.cpp:241
SocialIntegration::Initialize
static void Initialize()
Initialize the social integration system, loading any social integration plugins that are available.
Definition social_integration.cpp:160
SoundDriver::MainLoop
virtual void MainLoop()
Called once every tick.
Definition sound_driver.hpp:19
SoundDriver::GetInstance
static SoundDriver * GetInstance()
Get the currently active instance of the sound driver.
Definition sound_driver.hpp:35
StringConsumer
Parse data from a string / buffer.
Definition string_consumer.hpp:27
StringConsumer::TryReadIntegerBase
std::optional< T > TryReadIntegerBase(int base, bool clamp=false)
Try to read and parse an integer in number 'base', and then advance the reader.
Definition string_consumer.hpp:874
StringConsumer::AnyBytesLeft
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
Definition string_consumer.hpp:70
StringConsumer::ReadIf
bool ReadIf(std::string_view str)
Check whether the next data matches 'str', and skip it.
Definition string_consumer.hpp:454
TarScanner::Mode::Scenario
@ Scenario
Scan for scenarios and heightmaps.
TarScanner::Mode::Baseset
@ Baseset
Scan for base sets.
TarScanner::DoScan
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
Definition fileio.cpp:377
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition timer_game_calendar.h:31
TimerGameConst< struct Calendar >::INVALID_YEAR
static constexpr TimerGame< struct Calendar >::Year INVALID_YEAR
Representation of an invalid year.
Definition timer_game_common.h:192
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition timer_game_economy.h:38
TimerGameEconomy::year
static Year year
Current year, starting at 0.
Definition timer_game_economy.h:36
TimerGameEconomy::date_fract
static DateFract date_fract
Fractional part of the day.
Definition timer_game_economy.h:39
TimerGameRealtime::AUTOSAVE
@ AUTOSAVE
Only run when not paused or there was a Command executed recently.
Definition timer_game_realtime.h:33
TimerManager
The TimerManager manages a single Timer-type.
Definition timer_manager.h:25
TimerManager::Elapsed
static bool Elapsed(TElapsed value)
Called when time for this timer elapsed.
VideoDriver::GetInstance
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Definition video_driver.hpp:192
VideoDriver::MainLoop
virtual void MainLoop()=0
Perform the actual drawing.
command_func.h
Functions related to commands.
GetFirstPlayableCompanyID
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
Definition company_cmd.cpp:1354
UpdateLandscapingLimits
void UpdateLandscapingLimits()
Update the landscaping limits per company.
Definition company_cmd.cpp:342
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:119
_current_company
CompanyID _current_company
Company currently doing an action.
Definition company_cmd.cpp:56
company_cmd.h
Command definitions related to companies.
company_func.h
Functions related to companies.
IsLocalCompany
bool IsLocalCompany()
Is the current company the local company?
Definition company_func.h:47
company_gui.h
GUI Functions related to companies.
COMPANY_SPECTATOR
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
Definition company_type.h:21
COMPANY_NEW_COMPANY
static constexpr CompanyID COMPANY_NEW_COMPANY
The client wants a new company.
Definition company_type.h:20
OWNER_NONE
static constexpr Owner OWNER_NONE
The tile has no ownership.
Definition company_type.h:26
IConsoleCmdExec
void IConsoleCmdExec(std::string_view command_string, const uint recurse_count)
Execute a given command passed to us.
Definition console.cpp:269
console_func.h
Console functions used outside of the console code.
crashlog.h
Functions to be called to log a crash.
SetDebugString
void SetDebugString(std::string_view s, SetDebugStringErrorFunc error_func)
Set debugging levels by parsing the text in s.
Definition debug.cpp:144
DumpDebugFacilityNames
void DumpDebugFacilityNames(std::back_insert_iterator< std::string > &output_iterator)
Dump the available debug facility names in the help text.
Definition debug.cpp:88
DebugSendRemoteMessages
void DebugSendRemoteMessages()
Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the GameLoop threa...
Definition debug.cpp:235
Debug
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
_ini_videodriver
std::string _ini_videodriver
The video driver a stored in the configuration file.
Definition driver.cpp:27
_ini_musicdriver
std::string _ini_musicdriver
The music driver a stored in the configuration file.
Definition driver.cpp:34
_cur_resolution
Dimension _cur_resolution
The current resolution.
Definition driver.cpp:29
_ini_sounddriver
std::string _ini_sounddriver
The sound driver a stored in the configuration file.
Definition driver.cpp:32
SettingsDisableElrail
void SettingsDisableElrail(int32_t new_value)
_settings_game.disable_elrail callback
Definition elrail.cpp:575
elrail_func.h
header file for electrified rail specific functions
CheckEngines
void CheckEngines()
Check for engines that have an appropriate availability.
Definition engine.cpp:1313
engine_func.h
Functions related to engines.
error.h
Functions related to errors.
ScheduleErrorMessage
void ScheduleErrorMessage(ErrorList &datas)
Schedule a list of errors.
Definition error_gui.cpp:374
WL_ERROR
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition error.h:26
WL_CRITICAL
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition error.h:27
ShowErrorMessage
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Definition error_gui.cpp:296
error_func.h
Error reporting related functions.
factory.hpp
Factory to 'query' all available blitters.
_blitter_autodetected
bool _blitter_autodetected
Was the blitter autodetected or specified by the user?
Definition driver.cpp:37
_ini_blitter
std::string _ini_blitter
The blitter as stored in the configuration file.
Definition driver.cpp:36
DeterminePaths
void DeterminePaths(std::string_view exe, bool only_local_path)
Acquire the base paths (personal dir and game data dir), fill all other paths (save dir,...
Definition fileio.cpp:880
SaveLoadOperation
SaveLoadOperation
Operation performed on the file.
Definition fileio_type.h:52
SLO_CHECK
@ SLO_CHECK
Load file for checking and/or preview.
Definition fileio_type.h:53
SLO_SAVE
@ SLO_SAVE
File is being saved.
Definition fileio_type.h:55
SLO_LOAD
@ SLO_LOAD
File is being loaded.
Definition fileio_type.h:54
SLO_INVALID
@ SLO_INVALID
Unknown file operation.
Definition fileio_type.h:57
DetailedFileType
DetailedFileType
Kinds of files in each AbstractFileType.
Definition fileio_type.h:28
DFT_GAME_FILE
@ DFT_GAME_FILE
Save game or scenario file.
Definition fileio_type.h:31
DFT_OLD_GAME_FILE
@ DFT_OLD_GAME_FILE
Old save game or scenario file.
Definition fileio_type.h:30
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition fileio_type.h:88
NO_DIRECTORY
@ NO_DIRECTORY
A path without any base directory.
Definition fileio_type.h:107
SAVE_DIR
@ SAVE_DIR
Base directory for all savegames.
Definition fileio_type.h:90
AUTOSAVE_DIR
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
Definition fileio_type.h:91
BASESET_DIR
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
Definition fileio_type.h:96
FT_SCENARIO
@ FT_SCENARIO
old or new scenario
Definition fileio_type.h:20
FT_HEIGHTMAP
@ FT_HEIGHTMAP
heightmap file
Definition fileio_type.h:21
FT_SAVEGAME
@ FT_SAVEGAME
old or new savegame
Definition fileio_type.h:19
FiosGetScenarioListCallback
std::tuple< FiosType, std::string > FiosGetScenarioListCallback(SaveLoadOperation fop, std::string_view file, std::string_view ext)
Callback for FiosGetFileList.
Definition fios.cpp:441
FiosGetSavegameListCallback
std::tuple< FiosType, std::string > FiosGetSavegameListCallback(SaveLoadOperation fop, std::string_view file, std::string_view ext)
Callback for FiosGetFileList.
Definition fios.cpp:392
fios.h
Declarations for savegames operations.
_load_check_data
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition fios_gui.cpp:41
fontcache.h
Functions to read fonts from files and cache them.
framerate_type.h
Types for recording game performance data.
PFE_GAMELOOP
@ PFE_GAMELOOP
Speed of gameloop processing.
Definition framerate_type.h:48
PFE_GL_SHIPS
@ PFE_GL_SHIPS
Time spent processing ships.
Definition framerate_type.h:52
PFE_GL_AIRCRAFT
@ PFE_GL_AIRCRAFT
Time spent processing aircraft.
Definition framerate_type.h:53
PFE_GL_ECONOMY
@ PFE_GL_ECONOMY
Time spent processing cargo movement.
Definition framerate_type.h:49
PFE_GL_LANDSCAPE
@ PFE_GL_LANDSCAPE
Time spent processing other world features.
Definition framerate_type.h:54
PFE_GL_ROADVEHS
@ PFE_GL_ROADVEHS
Time spend processing road vehicles.
Definition framerate_type.h:51
PFE_GL_TRAINS
@ PFE_GL_TRAINS
Time spent processing trains.
Definition framerate_type.h:50
PFE_ALLSCRIPTS
@ PFE_ALLSCRIPTS
Sum of all GS/AI scripts.
Definition framerate_type.h:60
game.hpp
Base functions for all Games.
game_config.hpp
GameConfig stores the configuration settings of every Game.
_sl_version
SaveLoadVersion _sl_version
the major savegame version identifier
Definition saveload.cpp:81
_gamelog
Gamelog _gamelog
Gamelog instance.
Definition gamelog.cpp:31
gamelog.h
Functions to be called to log fundamental changes to the game.
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:243
GenerateWorld
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
Definition genworld.cpp:295
genworld.h
Functions related to world/map generation.
GENERATE_NEW_SEED
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
Definition genworld.h:25
GWM_HEIGHTMAP
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
Definition genworld.h:32
GWM_EMPTY
@ GWM_EMPTY
Generate an empty map (sea-level)
Definition genworld.h:30
GWM_RANDOM
@ GWM_RANDOM
Generate a random map for SE.
Definition genworld.h:31
GWM_NEWGAME
@ GWM_NEWGAME
Generate a map for a new game.
Definition genworld.h:29
getoptdata.h
Library for parsing command-line options.
ODF_OPTIONAL_VALUE
@ ODF_OPTIONAL_VALUE
An option with an optional value.
Definition getoptdata.h:17
ODF_NO_VALUE
@ ODF_NO_VALUE
A plain option (no value attached to it).
Definition getoptdata.h:15
ODF_HAS_VALUE
@ ODF_HAS_VALUE
An option with a value.
Definition getoptdata.h:16
_game_session_stats
GameSessionStats _game_session_stats
Statistics about the current session.
Definition gfx.cpp:51
UpdateGUIZoom
void UpdateGUIZoom()
Resolve GUI zoom level, if auto-suggestion is requested.
Definition gfx.cpp:1790
_pause_mode
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:50
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition gfx.cpp:49
gfx_layout.h
Functions related to laying out the texts.
S8BPP_NONE
@ S8BPP_NONE
No support for 8bpp by OS or hardware, force 32bpp blitters.
Definition gfx_type.h:381
FONTSIZES_REQUIRED
constexpr FontSizes FONTSIZES_REQUIRED
Mask of font sizes required to be present.
Definition gfx_type.h:264
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1549
gui.h
GUI functions that shouldn't be here.
LoadFromHighScore
void LoadFromHighScore()
Initialize the highscore table to 0 and if any file exists, load in values.
Definition highscore.cpp:139
SaveToHighScore
void SaveToHighScore()
Save HighScore table to file.
Definition highscore.cpp:116
highscore.h
Declaration of functions and types defined in highscore.h and highscore_gui.h.
LoadHotkeysFromConfig
void LoadHotkeysFromConfig()
Load the hotkeys from the config file.
Definition hotkeys.cpp:332
SaveHotkeysToConfig
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
Definition hotkeys.cpp:338
hotkeys.h
Hotkey related functions.
industry.h
Base of all industries.
CheckIndustries
void CheckIndustries()
Verify whether the generated industries are complete, and warn the user if not.
Definition industry_cmd.cpp:3160
RunTileLoop
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every TILE_UPDATE_FREQU...
Definition landscape.cpp:798
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:169
linkgraphschedule.h
Declaration of link graph schedule used for cargo distribution.
SetupColoursAndInitialWindow
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
Definition main_gui.cpp:553
GenerateSavegameId
void GenerateSavegameId()
Generate an unique savegame ID.
Definition misc.cpp:87
misc_cmd.h
Miscellaneous command definitions.
mixer.h
Functions to mix sound samples.
music_driver.hpp
Base for all music playback.
NetworkStartUp
void NetworkStartUp()
This tries to launch the network for a given OS.
Definition network.cpp:1286
_is_network_server
bool _is_network_server
Does this client wants to be a network-server?
Definition network.cpp:71
NetworkClientJoinGame
void NetworkClientJoinGame()
Actually perform the joining to the server.
Definition network.cpp:819
NetworkOnGameStart
void NetworkOnGameStart()
Perform tasks when the server is started.
Definition network.cpp:946
_network_available
bool _network_available
is network mode available?
Definition network.cpp:69
_network_reconnect
uint8_t _network_reconnect
Reconnect timeout.
Definition network.cpp:74
_networking
bool _networking
are we in networking mode?
Definition network.cpp:67
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:70
NetworkDisconnect
void NetworkDisconnect(bool close_admins)
We want to disconnect from the host/clients.
Definition network.cpp:1000
_network_server
bool _network_server
network-server is active
Definition network.cpp:68
NetworkBackgroundLoop
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
Definition network.cpp:1081
_network_bind_list
StringList _network_bind_list
The addresses to bind on.
Definition network.cpp:75
NetworkClientConnectGame
bool NetworkClientConnectGame(std::string_view connection_string, CompanyID default_company, const std::string &join_server_password)
Join a client to the server at with the given connection string.
Definition network.cpp:786
NetworkShutDown
void NetworkShutDown()
This shuts the network down.
Definition network.cpp:1304
ParseFullConnectionString
std::string_view ParseFullConnectionString(std::string_view connection_string, uint16_t &port, CompanyID *company_id)
Converts a string to ip/port/company Format: IP:port::company.
Definition network.cpp:520
network.h
Basic functions/variables used all over the place.
network_func.h
Network functions used by other parts of OpenTTD.
ShowNetworkAskSurvey
void ShowNetworkAskSurvey()
Show a modal confirmation window with "no" / "preview" / "yes" buttons.
Definition network_gui.cpp:2326
network_gui.h
GUIs related to networking.
network_survey.h
Part of the network protocol handling opt-in survey.
_loaded_newgrf_features
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition newgrf.cpp:74
ResetNewGRFData
void ResetNewGRFData()
Reset all NewGRF loaded data.
Definition newgrf.cpp:408
newgrf.h
Base for the NewGRF implementation.
UpdateNewGRFConfigPalette
void UpdateNewGRFConfigPalette(int32_t)
Update the palettes of the graphics from the config file.
Definition newgrf_config.cpp:215
ResetGRFConfig
void ResetGRFConfig(bool defaults)
Reset the current GRF Config to either blank or newgame settings.
Definition newgrf_config.cpp:407
ScanNewGRFFiles
void ScanNewGRFFiles(NewGRFScanCallback *callback)
Scan for all NewGRFs.
Definition newgrf_config.cpp:578
_skip_all_newgrf_scanning
int _skip_all_newgrf_scanning
Set this flag to prevent any NewGRF scanning from being done.
Definition newgrf_config.cpp:481
Compatible
@ Compatible
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches)
Definition newgrf_config.h:24
PSM_ENTER_GAMELOOP
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
Definition newgrf_storage.h:21
PSM_LEAVE_GAMELOOP
@ PSM_LEAVE_GAMELOOP
Leave the gameloop, changes will be temporary.
Definition newgrf_storage.h:22
news_func.h
Functions related to news.
MusicLoop
void MusicLoop()
Check music playback status and start/stop/song-finished.
Definition music_gui.cpp:453
FatalErrorI
void FatalErrorI(const std::string &str)
Error handling for fatal non-user errors.
Definition openttd.cpp:140
openttd_main
int openttd_main(std::span< std::string_view > arguments)
Main entry point for this lovely game.
Definition openttd.cpp:500
OnStartScenario
static void OnStartScenario()
Triggers everything required to set up a saved scenario for a new game.
Definition openttd.cpp:833
DoStartupNewCompany
Company * DoStartupNewCompany(bool is_ai, CompanyID company=CompanyID::Invalid())
Create a new company and sets all company variables default values.
Definition company_cmd.cpp:598
OnStartGame
static void OnStartGame(bool dedicated_server)
Triggers everything that should be triggered when starting a game.
Definition openttd.cpp:848
ParseResolution
static void ParseResolution(Dimension &res, std::string_view s)
Extract the resolution from the given string and store it in the 'res' parameter.
Definition openttd.cpp:274
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:941
ChangeAutosaveFrequency
void ChangeAutosaveFrequency(bool reset)
Reset the interval of the autosave.
Definition openttd.cpp:1314
StateGameLoop
void StateGameLoop()
State controlling game loop.
Definition openttd.cpp:1210
UserErrorI
void UserErrorI(const std::string &str)
Error handling for fatal user errors.
Definition openttd.cpp:119
ShowHelp
static void ShowHelp()
Show the help message when someone passed a wrong parameter.
Definition openttd.cpp:154
RequestNewGRFScan
bool RequestNewGRFScan(NewGRFScanCallback *callback)
Request a new NewGRF scan.
Definition openttd.cpp:1327
ShutdownGame
static void ShutdownGame()
Uninitializes drivers, frees allocated memory, cleans pools, ... Generally, prepares the game for shu...
Definition openttd.cpp:294
LoadIntroGame
static void LoadIntroGame(bool load_newgrfs=true)
Load the introduction game.
Definition openttd.cpp:325
CreateOptions
static std::vector< OptionData > CreateOptions()
Create all the options that OpenTTD supports.
Definition openttd.cpp:477
CallWindowGameTickEvent
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
Definition window.cpp:3326
CheckCaches
void CheckCaches()
Check the validity of some of the caches.
Definition cachecheck.cpp:36
_config_file
std::string _config_file
Configuration file of OpenTTD.
Definition settings.cpp:64
HandleBootstrap
bool HandleBootstrap()
Handle all procedures for bootstrapping OpenTTD without a base graphics set.
Definition bootstrap_gui.cpp:363
_autosave_interval
static IntervalTimer< TimerGameRealtime > _autosave_interval({std::chrono::milliseconds::zero(), TimerGameRealtime::AUTOSAVE}, [](auto) { _pause_mode.Reset(PauseMode::CommandDuringPause);_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.
DO_FULL_ANIMATION
@ DO_FULL_ANIMATION
Perform palette animation.
Definition openttd.h:49
PauseMode::Normal
@ Normal
A game normally paused.
PauseMode::CommandDuringPause
@ CommandDuringPause
A game paused, and a command executed during the pause; resets on autosave.
PauseMode::SaveLoad
@ SaveLoad
A game paused for saving/loading.
GameMode
GameMode
Mode which defines the state of the game.
Definition openttd.h:18
SwitchMode
SwitchMode
Mode which defines what mode we're switching to.
Definition openttd.h:26
SM_START_HEIGHTMAP
@ SM_START_HEIGHTMAP
Load a heightmap and start a new game from it.
Definition openttd.h:38
SM_RESTART_HEIGHTMAP
@ SM_RESTART_HEIGHTMAP
Load a heightmap and start a new game from it with current settings.
Definition openttd.h:40
SM_LOAD_SCENARIO
@ SM_LOAD_SCENARIO
Load scenario from scenario editor.
Definition openttd.h:37
SM_GENRANDLAND
@ SM_GENRANDLAND
Generate random land within scenario editor.
Definition openttd.h:36
SM_JOIN_GAME
@ SM_JOIN_GAME
Join a network game.
Definition openttd.h:41
SM_MENU
@ SM_MENU
Switch to game intro menu.
Definition openttd.h:33
SM_RESTARTGAME
@ SM_RESTARTGAME
Restart --> 'Random game' with current settings.
Definition openttd.h:29
SM_RELOADGAME
@ SM_RELOADGAME
Reload the savegame / scenario / heightmap you started the game with.
Definition openttd.h:30
SM_SAVE_HEIGHTMAP
@ SM_SAVE_HEIGHTMAP
Save heightmap.
Definition openttd.h:35
SM_LOAD_HEIGHTMAP
@ SM_LOAD_HEIGHTMAP
Load heightmap from scenario editor.
Definition openttd.h:39
SM_SAVE_GAME
@ SM_SAVE_GAME
Save game.
Definition openttd.h:34
SM_LOAD_GAME
@ SM_LOAD_GAME
Load game, Play Scenario.
Definition openttd.h:32
SM_EDITOR
@ SM_EDITOR
Switch to scenario editor.
Definition openttd.h:31
SM_NEWGAME
@ SM_NEWGAME
New Game --> 'Random game'.
Definition openttd.h:28
progress.h
Functions related to modal progress.
HasModalProgress
bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition progress.h:17
InitializeRailGUI
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
Definition rail_gui.cpp:2015
rail_gui.h
Functions/types etc.
random_func.hpp
Pseudo random number generator.
rev.h
declaration of OTTD revision dependent variables
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:1760
road_gui.h
Functions/types related to the road GUIs.
roadstop_base.h
Base class for roadstops.
roadveh.h
Road vehicle states.
safeguards.h
A number of safeguards to prevent using unsafe methods.
ProcessAsyncSaveFinish
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition saveload.cpp:394
LoadWithFilter
SaveOrLoadResult LoadWithFilter(std::shared_ptr< LoadFilter > reader)
Load the game using a (reader) filter.
Definition saveload.cpp:3238
_do_autosave
bool _do_autosave
are we doing an autosave at the moment?
Definition saveload.cpp:84
DoAutoOrNetsave
void DoAutoOrNetsave(FiosNumberedSaveName &counter)
Create an autosave or netsave.
Definition saveload.cpp:3349
GetSaveLoadErrorType
EncodedString GetSaveLoadErrorType()
Return the appropriate initial string for an error depending on whether we are saving or loading.
Definition saveload.cpp:2967
SaveOrLoad
SaveOrLoadResult SaveOrLoad(std::string_view 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:3258
_file_to_saveload
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition saveload.cpp:78
DoExitSave
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition saveload.cpp:3367
GetSaveLoadErrorMessage
EncodedString GetSaveLoadErrorMessage()
Return the description of the error.
Definition saveload.cpp:2973
saveload.h
Functions/types related to saving and loading games.
SaveOrLoadResult
SaveOrLoadResult
Save or load result codes.
Definition saveload.h:420
SL_OK
@ SL_OK
completed successfully
Definition saveload.h:421
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:423
SaveLoadVersion
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
Definition saveload.h:30
MakeHeightmapScreenshot
bool MakeHeightmapScreenshot(std::string_view filename)
Make a heightmap of the current map.
Definition screenshot.cpp:314
screenshot.h
Functions to make screenshots.
LoadFromConfig
void LoadFromConfig(bool startup)
Load the values from the configuration files.
Definition settings.cpp:1375
SaveToConfig
void SaveToConfig()
Save the values to the configuration file.
Definition settings.cpp:1469
_old_vds
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Definition settings.cpp:63
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
_settings_newgame
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition settings.cpp:62
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
settings_func.h
Functions related to setting/changing the settings.
ship.h
Base for ships.
social_integration.h
Interface definitions for game to report/respond to social integration.
sound_driver.hpp
Base for all sound drivers.
station_base.h
Base classes/functions for stations.
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
FormatArrayAsHex
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:77
string_consumer.hpp
Parse strings.
ParseInteger
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
Definition string_consumer.hpp:917
GetEncodedString
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
CheckForMissingGlyphs
void CheckForMissingGlyphs(MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
Definition strings.cpp:2390
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:424
InitializeLanguagePacks
void InitializeLanguagePacks()
Make a list of the available language packs.
Definition strings.cpp:2249
strings_func.h
Functions related to OTTD's strings.
AfterNewGRFScan
Callback structure of statements to be executed after the NewGRF scan.
Definition openttd.cpp:374
AfterNewGRFScan::dedicated_host
std::string dedicated_host
Hostname for the dedicated server.
Definition openttd.cpp:377
AfterNewGRFScan::startyear
TimerGameCalendar::Year startyear
The start year.
Definition openttd.cpp:375
AfterNewGRFScan::OnNewGRFsScanned
void OnNewGRFsScanned() override
Called whenever the NewGRF scan completed.
Definition openttd.cpp:393
AfterNewGRFScan::dedicated_port
uint16_t dedicated_port
Port for the dedicated server.
Definition openttd.cpp:378
AfterNewGRFScan::save_config
bool save_config
The save config setting.
Definition openttd.cpp:381
AfterNewGRFScan::connection_string
std::string connection_string
Information about the server to connect to.
Definition openttd.cpp:379
AfterNewGRFScan::generation_seed
uint32_t generation_seed
Seed for the new game.
Definition openttd.cpp:376
AfterNewGRFScan::join_server_password
std::string join_server_password
The password to join the server with.
Definition openttd.cpp:380
AfterNewGRFScan::AfterNewGRFScan
AfterNewGRFScan()
Create a new callback.
Definition openttd.cpp:386
Backup
Class to backup a specific variable and restore it later.
Definition backup_type.hpp:21
Backup::Restore
void Restore()
Restore the variable.
Definition backup_type.hpp:110
BaseGraphics::Ini::extra_version
uint32_t extra_version
version of the extra GRF
Definition base_media_graphics.h:67
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:53
BaseSet::name
std::string name
The name of the base set.
Definition base_media_base.h:62
ClientSettings::company
CompanySettings company
default values for per-company settings
Definition settings_type.h:652
ClientSettings::music
MusicSettings music
settings related to music/sound
Definition settings_type.h:654
ClientSettings::network
NetworkSettings network
settings related to the network
Definition settings_type.h:651
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition settings_type.h:650
CommandHelper
Definition command_func.h:84
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition company_base.h:124
CompanySettings::vehicle
VehicleDefaultSettings vehicle
default settings for vehicles
Definition settings_type.h:615
Company
Definition company_base.h:127
CursorVars::fix_at
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
Definition gfx_type.h:128
CursorVars::in_window
bool in_window
mouse inside this window, determines drawing logic
Definition gfx_type.h:147
Dimension
Dimensions (a width and height) of a rectangle in 2D.
Definition geometry_type.hpp:56
EngineOverrideManager::ResetToCurrentNewGRFConfig
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
Definition engine.cpp:584
FileToSaveLoad::SetMode
void SetMode(const FiosType &ft, SaveLoadOperation fop=SLO_LOAD)
Set the mode and file type of the file to save or load.
Definition saveload.cpp:3421
FileToSaveLoad::ftype
FiosType ftype
File type.
Definition saveload.h:429
FileToSaveLoad::file_op
SaveLoadOperation file_op
File operation to perform.
Definition saveload.h:428
FileToSaveLoad::name
std::string name
Name of the file.
Definition saveload.h:430
FiosNumberedSaveName
A savegame name automatically numbered.
Definition fios.h:128
FiosType::detailed
DetailedFileType detailed
Detailed file type.
Definition fileio_type.h:65
FiosType::abstract
AbstractFileType abstract
Abstract file type.
Definition fileio_type.h:64
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition newgrf_config.h:158
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:66
GRFLoadedFeatures::used_liveries
uint64_t used_liveries
Bitmask of LiveryScheme used by the defined engines.
Definition newgrf.h:190
GUISettings::last_newgrf_count
uint32_t last_newgrf_count
the numbers of NewGRFs we found during the last scan
Definition settings_type.h:227
GUISettings::starting_colour_secondary
Colours starting_colour_secondary
default secondary colour scheme for the company to start a new game with
Definition settings_type.h:232
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:197
GUISettings::pause_on_newgame
bool pause_on_newgame
whether to start new games paused or not
Definition settings_type.h:208
GUISettings::autosave_interval
uint32_t autosave_interval
how often should we do autosaves?
Definition settings_type.h:194
GUISettings::starting_colour
Colours starting_colour
default colour scheme for the company to start a new game with
Definition settings_type.h:231
GameCreationSettings::map_x
uint8_t map_x
X size of map.
Definition settings_type.h:382
GameCreationSettings::map_y
uint8_t map_y
Y size of map.
Definition settings_type.h:383
GameCreationSettings::starting_year
TimerGameCalendar::Year starting_year
starting date
Definition settings_type.h:380
GameCreationSettings::generation_seed
uint32_t generation_seed
noise seed for world generation
Definition settings_type.h:379
GameSessionStats::start_time
std::chrono::steady_clock::time_point start_time
Time when the current game was started.
Definition openttd.h:56
GameSessionStats::savegame_size
std::optional< size_t > savegame_size
Size of the last saved savegame in bytes, or std::nullopt if not saved yet.
Definition openttd.h:58
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition settings_type.h:634
GameSettings::script_config
ScriptConfigSettings script_config
AI and Gamescript configuration.
Definition settings_type.h:638
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition settings_type.h:641
GetOptData
Data storage for parsing command line options.
Definition getoptdata.h:29
GetOptData::opt
std::string_view opt
Option value, if available (else empty).
Definition getoptdata.h:35
GetOptData::arguments
ArgumentSpan arguments
Remaining command line arguments.
Definition getoptdata.h:33
GetOptData::GetOpt
int GetOpt()
Find the next option.
Definition getoptdata.cpp:22
GraphicsSet::GetOrCreateExtraConfig
GRFConfig & GetOrCreateExtraConfig() const
Return configuration for the extra GRF, or lazily create it.
Definition gfxinit.cpp:378
Industry
Defines the internal data of a functional industry.
Definition industry.h:62
LoadCheckData::HasNewGrfs
bool HasNewGrfs()
Check whether the game uses any NewGrfs.
Definition fios.h:67
LoadCheckData::error_msg
std::string error_msg
Data to pass to string parameters when displaying error.
Definition fios.h:36
LoadCheckData::error
StringID error
Error message from loading. INVALID_STRING_ID if no error.
Definition fios.h:35
LoadCheckData::HasErrors
bool HasErrors()
Check whether loading the game resulted in errors.
Definition fios.h:58
LoadCheckData::Clear
void Clear()
Reset read data.
Definition fios_gui.cpp:49
Map::SizeX
static uint SizeX()
Get the size of the map along the X.
Definition map_func.h:272
Map::SizeY
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:281
MusicSettings::effect_vol
uint8_t effect_vol
The requested effects volume.
Definition settings_type.h:286
MusicSettings::music_vol
uint8_t music_vol
The requested music volume.
Definition settings_type.h:285
NetworkSettings::reload_cfg
bool reload_cfg
reload the config file before restarting
Definition settings_type.h:369
NetworkSettings::server_port
uint16_t server_port
port the server listens on
Definition settings_type.h:343
NetworkSettings::last_joined
std::string last_joined
Last joined server.
Definition settings_type.h:370
NetworkSettings::participate_survey
ParticipateSurvey participate_survey
Participate in the automated survey.
Definition settings_type.h:372
NewGRFScanCallback
Callback for NewGRF scanning.
Definition newgrf_config.h:222
PoolBase::Clean
static void Clean(PoolTypes)
Clean all pools of given type.
Definition pool_func.cpp:30
PoolID< uint8_t, struct CompanyIDTag, 0xF, 0xFF >
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:436
Pool::PoolItem<&_company_pool >::Get
static Titem * Get(auto index)
Returns Titem with given index.
Definition pool_type.hpp:387
ScriptConfigSettings::game
std::unique_ptr< class GameConfig > game
settings for gamescript
Definition settings_type.h:622
ScriptConfigSettings::ai
TypedIndexContainer< std::array< std::unique_ptr< class AIConfig >, MAX_COMPANIES >, CompanyID > ai
settings per company
Definition settings_type.h:621
StrongType::Typedef
Templated helper to make a type-safe 'typedef' representing a single POD value.
Definition strong_typedef_type.hpp:130
VehicleSettings::disable_elrails
bool disable_elrails
when true, the elrails are disabled
Definition settings_type.h:525
WindowDesc::SaveToConfig
static void SaveToConfig()
Save all WindowDesc settings to _windows_file.
Definition window.cpp:176
WindowDesc::LoadFromConfig
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
Definition window.cpp:155
subsidy_func.h
Functions related to subsidies.
timer.h
Definition of Interval and OneShot timers.
timer_game_calendar.h
Definition of the game-calendar-timer.
timer_game_economy.h
Definition of the game-economy-timer.
timer_game_realtime.h
Definition of the real time game-timer.
timer_game_tick.h
Definition of the tick-based game-timer.
town.h
Base of the town class.
train.h
Base for the train class.
_display_opt
uint8_t _display_opt
What do we want to draw/do?
Definition transparency_gui.cpp:26
RunVehicleCalendarDayProc
void RunVehicleCalendarDayProc()
Age all vehicles, spreading out the action using the current TimerGameCalendar::date_fract.
Definition vehicle.cpp:907
vehicle_func.h
Functions related to vehicles.
video_driver.hpp
Base of all video drivers.
InitializeSpriteSorter
void InitializeSpriteSorter()
Choose the "best" sprite sorter and set _vp_sprite_sorter.
Definition viewport.cpp:3605
viewport_func.h
Functions related to (drawing on) viewports.
viewport_sprite_sorter.h
Types related to sprite sorting.
OTTD2FS
std::wstring OTTD2FS(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:357
FS2OTTD
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:340
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:1195
ResetWindowSystem
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition window.cpp:1895
UnInitWindowSystem
void UnInitWindowSystem()
Close down the windowing system.
Definition window.cpp:1881
InitWindowSystem
void InitWindowSystem()
(re)initialize the windowing system
Definition window.cpp:1859
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3179
WC_STATUS_BAR
@ WC_STATUS_BAR
Statusbar (at the bottom of your screen); Window numbers:
Definition window_type.h:69
WC_SAVELOAD
@ WC_SAVELOAD
Saveload window; Window numbers:
Definition window_type.h:149
ZoomLevel::Min
@ Min
Minimum zoom level.