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