OpenTTD Source 20261112-master-gbcbec5e63f
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
9
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_graphics.h"
24#include "base_media_music.h"
25#include "base_media_sounds.h"
26#include "saveload/saveload.h"
28#include "company_cmd.h"
29#include "company_func.h"
30#include "command_func.h"
31#include "news_func.h"
32#include "fios.h"
33#include "console_func.h"
34#include "spritecache.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 "engine_base.h"
48#include "elrail_func.h"
49#include "landscape.h"
50#include "rev.h"
51#include "highscore.h"
52#include "crashlog.h"
53#include "engine_func.h"
54#include "core/random_func.hpp"
55#include "rail_gui.h"
56#include "core/backup_type.hpp"
57#include "hotkeys.h"
58#include "newgrf.h"
59#include "misc/getoptdata.h"
60#include "game/game.hpp"
61#include "game/game_config.hpp"
62#include "viewport_func.h"
64#include "framerate_type.h"
65#include "industry.h"
66#include "network/network_gui.h"
68#include "misc_cmd.h"
69#include "timer/timer.h"
74#include "social_integration.h"
76#include "window_func.h"
77
79
80#include <system_error>
81
82#include "table/strings.h"
83
84#ifdef __EMSCRIPTEN__
85# include <emscripten.h>
86# include <emscripten/html5.h>
87#endif
88
89#include "safeguards.h"
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(std::string_view 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, 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 std::_Exit(1);
126}
127
128/* Doxygen in error_func.h */
129void FatalErrorI(const std::string &str)
130{
131 if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
132 ShowOSErrorBox(str, true);
133 }
134
135 /* Set the error message for the crash log and then invoke it. */
137 abort();
138}
139
143static void ShowHelp()
144{
145 std::string str;
146 str.reserve(8192);
147
148 std::back_insert_iterator<std::string> output_iterator = std::back_inserter(str);
149 fmt::format_to(output_iterator, "OpenTTD {}\n", _openttd_revision);
150 str +=
151 "\n"
152 "\n"
153 "Command line options:\n"
154 " -v drv = Set video driver (see below)\n"
155 " -s drv = Set sound driver (see below)\n"
156 " -m drv = Set music driver (see below)\n"
157 " -b drv = Set the blitter to use (see below)\n"
158 " -r res = Set resolution (for instance 800x600)\n"
159 " -h = Display this help text\n"
160 " -t year = Set starting year\n"
161 " -d [[fac=]lvl[,...]]= Debug mode\n"
162 " -e = Start Editor\n"
163 " -g [savegame|scenario|heightmap] = Start new/savegame/scenario/heightmap immediately\n"
164 " -G seed = Set random seed\n"
165 " -n host[:port][#company]= Join network game\n"
166 " -p password = Password to join server\n"
167 " -D [host][:port] = Start dedicated server\n"
168#if !defined(_WIN32)
169 " -f = Fork into the background (dedicated only)\n"
170#endif
171 " -I graphics_set = Force the graphics set (see below)\n"
172 " -S sounds_set = Force the sounds set (see below)\n"
173 " -M music_set = Force the music set (see below)\n"
174 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
175 " -x = Never save configuration changes to disk\n"
176 " -X = Don't use global folders to search for files\n"
177 " -q savegame = Write some information about the savegame and exit\n"
178 " -Q = Don't scan for/load NewGRF files on startup\n"
179 " -QQ = Disable NewGRF scanning/loading entirely\n"
180 "\n";
181
182 /* List the graphics packs */
183 BaseGraphics::GetSetsList(output_iterator);
184
185 /* List the sounds packs */
186 BaseSounds::GetSetsList(output_iterator);
187
188 /* List the music packs */
189 BaseMusic::GetSetsList(output_iterator);
190
191 /* List the drivers */
192 DriverFactoryBase::GetDriversInfo(output_iterator);
193
194 /* List the blitters */
195 BlitterFactory::GetBlittersInfo(output_iterator);
196
197 /* List the debug facilities. */
198 DumpDebugFacilityNames(output_iterator);
199
200 /* We need to initialize the AI, so it finds the AIs */
202 AI::GetConsoleList(output_iterator, true);
203 AI::Uninitialize(true);
204
205 /* We need to initialize the GameScript, so it finds the GSs */
207 Game::GetConsoleList(output_iterator, true);
208 Game::Uninitialize(true);
209
210 /* ShowInfo put output to stderr, but version information should go
211 * to stdout; this is the only exception */
212#if !defined(_WIN32)
213 fmt::print("{}\n", str);
214#else
215 ShowInfoI(str);
216#endif
217}
218
219static void WriteSavegameInfo(const std::string &name)
220{
222 uint32_t last_ottd_rev = 0;
223 uint8_t ever_modified = 0;
224 bool removed_newgrfs = false;
225
226 _gamelog.Info(&last_ottd_rev, &ever_modified, &removed_newgrfs);
227
228 std::string message;
229 message.reserve(1024);
230 format_append(message, "Name: {}\n", name);
231 format_append(message, "Savegame ver: {}\n", _sl_version);
232 format_append(message, "NewGRF ver: 0x{:08X}\n", last_ottd_rev);
233 format_append(message, "Modified: {}\n", ever_modified);
234
235 if (removed_newgrfs) {
236 format_append(message, "NewGRFs have been removed\n");
237 }
238
239 message += "NewGRFs:\n";
240 if (_load_check_data.HasNewGrfs()) {
241 for (const auto &c : _load_check_data.grfconfig) {
242 format_append(message, "{} {} {}\n", FormatArrayAsHex(c->ident.grfid),
243 FormatArrayAsHex(c->flags.Test(GRFConfigFlag::Compatible) ? c->original_md5sum : c->ident.md5sum), c->filename);
244 }
245 }
246
247 /* ShowInfo put output to stderr, but version information should go
248 * to stdout; this is the only exception */
249#if !defined(_WIN32)
250 fmt::print("{}\n", message);
251#else
252 ShowInfoI(message);
253#endif
254}
255
256
263static void ParseResolution(Dimension &res, std::string_view s)
264{
265 StringConsumer consumer(s);
266 auto width = consumer.TryReadIntegerBase<uint>(10);
267 auto valid = consumer.ReadIf("x");
268 auto height = consumer.TryReadIntegerBase<uint>(10);
269 if (!width.has_value() || !valid || !height.has_value() || consumer.AnyBytesLeft()) {
270 ShowInfo("Invalid resolution '{}'", s);
271 return;
272 }
273
274 res.width = std::max<uint>(*width, 64);
275 res.height = std::max<uint>(*height, 64);
276}
277
278
283static void ShutdownGame()
284{
285 IConsoleFree();
286
287 if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
288
291
293
294 /* stop the scripts */
295 AI::Uninitialize(false);
296 Game::Uninitialize(false);
297
298 /* Uninitialize variables that are allocated dynamically */
299 _gamelog.Reset();
300
302 PoolBase::Clean(PT_ALL);
303
305}
306
311static void LoadIntroGame(bool load_newgrfs = true)
312{
313 _game_mode = GameMode::Menu;
314
315 if (load_newgrfs) ResetGRFConfig(false);
316
317 /* Setup main window */
320
321 /* Load the default opening screen savegame */
323 GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
325 } else {
326 SetLocalCompany(CompanyID::Begin());
327 }
328
329 FixTitleGameZoom();
330 _pause_mode = {};
331 _cursor.fix_at = false;
332
334
335 MusicLoop(); // ensure music is correct
336}
337
338void MakeNewgameSettingsLive()
339{
340 for (CompanyID c = CompanyID::Begin(); c < MAX_COMPANIES; ++c) {
341 _settings_game.script_config.ai[c].reset();
342 }
343 _settings_game.script_config.game.reset();
344
345 /* Copy newgame settings to active settings.
346 * Also initialise old settings needed for savegame conversion. */
348 _old_vds = _settings_client.company.vehicle;
349}
350
351void OpenBrowser(const std::string &url)
352{
353 /* Make sure we only accept urls that are sure to open a browser. */
354 if (url.starts_with("http://") || url.starts_with("https://")) {
355 OSOpenBrowser(url);
356 }
357}
358
363 std::string dedicated_host;
364 uint16_t dedicated_port = 0;
365 std::string connection_string;
367 bool save_config = true;
368
373 {
374 /* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
375 * if it's placed outside a member function, directly in the struct body. */
376 static_assert(sizeof(generation_seed) == sizeof(_settings_game.game_creation.generation_seed));
377 }
378
379 void OnNewGRFsScanned() override
380 {
381 ResetGRFConfig(false);
382
384
387
388 /* We want the new (correct) NewGRF count to survive the loading. */
389 uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
391 _settings_client.gui.last_newgrf_count = last_newgrf_count;
392 /* Since the default for the palette might have changed due to
393 * reading the configuration file, recalculate that now. */
395
396 Game::Uninitialize(true);
397 AI::Uninitialize(true);
401
402 /* We have loaded the config, so we may possibly save it. */
403 _save_config = save_config;
404
405 /* restore saved music and effects volumes */
407 SetEffectVolume(_settings_client.music.effect_vol);
408
409 if (startyear != CalendarTime::INVALID_YEAR) IConsoleSetSetting("game_creation.starting_year", startyear.base());
410 _settings_newgame.game_creation.generation_seed = generation_seed;
411
412 if (!dedicated_host.empty()) {
413 _network_bind_list.clear();
415 }
416 if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
417
418 /* initialize the ingame console */
419 IConsoleInit();
420 InitializeGUI();
421 IConsoleCmdExec("exec scripts/autoexec.scr 0");
422
423 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
424 if (_switch_mode != SwitchMode::None) MakeNewgameSettingsLive();
425
426 if (_network_available && !connection_string.empty()) {
429
431 }
432
433 /* After the scan we're not used anymore. */
434 delete this;
435 }
436};
437
438void PostMainLoop()
439{
440 WaitTillSaved();
441
442 /* only save config if we have to */
443 if (_save_config) {
444 SaveToConfig();
448 }
449
450 /* Reset windowing system, stop drivers, free used memory, ... */
451 ShutdownGame();
452}
453
454#if defined(UNIX)
455extern void DedicatedFork();
456#endif
457
463static std::vector<OptionData> CreateOptions()
464{
465 std::vector<OptionData> options;
466 /* Options that require a parameter. */
467 for (char c : "GIMSbcmnpqrstv") options.push_back({ .type = ODF_HAS_VALUE, .id = c, .shortname = c });
468
469 /* Options with an optional parameter. */
470 for (char c : "Ddg") options.push_back({ .type = ODF_OPTIONAL_VALUE, .id = c, .shortname = c });
471
472 /* Options without a parameter. */
473 for (char c : "QXehx") options.push_back({ .type = ODF_NO_VALUE, .id = c, .shortname = c });
474#if !defined(_WIN32)
475 options.push_back({ .type = ODF_NO_VALUE, .id = 'f', .shortname = 'f' });
476#endif
477
478 return options;
479}
480
486int openttd_main(std::span<std::string_view> arguments)
487{
488 _game_session_stats.start_time = std::chrono::steady_clock::now();
489 _game_session_stats.savegame_size = std::nullopt;
490
491 std::string musicdriver;
492 std::string sounddriver;
493 std::string videodriver;
494 std::string blitter;
495 std::string graphics_set;
496 std::string sounds_set;
497 std::string music_set;
498 Dimension resolution = {0, 0};
499 std::unique_ptr<AfterNewGRFScan> scanner = std::make_unique<AfterNewGRFScan>();
500 bool dedicated = false;
501 bool only_local_path = false;
502
503 extern bool _dedicated_forks;
504 _dedicated_forks = false;
505
506 _game_mode = GameMode::Menu;
508
509 auto options = CreateOptions();
510 GetOptData mgo(arguments.subspan(1), options);
511
512 int i;
513 while ((i = mgo.GetOpt()) != -1) {
514 switch (i) {
515 case 'I': graphics_set = mgo.opt; break;
516 case 'S': sounds_set = mgo.opt; break;
517 case 'M': music_set = mgo.opt; break;
518 case 'm': musicdriver = mgo.opt; break;
519 case 's': sounddriver = mgo.opt; break;
520 case 'v': videodriver = mgo.opt; break;
521 case 'b': blitter = mgo.opt; break;
522 case 'D':
523 musicdriver = "null";
524 sounddriver = "null";
525 videodriver = "dedicated";
526 blitter = "null";
527 dedicated = true;
528 SetDebugString("net=4", ShowInfoI);
529 if (!mgo.opt.empty()) {
530 scanner->dedicated_host = ParseFullConnectionString(mgo.opt, scanner->dedicated_port);
531 }
532 break;
533 case 'f': _dedicated_forks = true; break;
534 case 'n':
535 scanner->connection_string = mgo.opt; // host:port#company parameter
536 break;
537 case 'p':
538 scanner->join_server_password = mgo.opt;
539 break;
540 case 'r': ParseResolution(resolution, mgo.opt); break;
541 case 't':
542 if (auto value = ParseInteger(mgo.opt); value.has_value()) {
543 scanner->startyear = TimerGameCalendar::Year(*value);
544 } else {
545 fmt::print(stderr, "Invalid start year: {}\n", mgo.opt);
546 }
547 break;
548 case 'd': {
549#if defined(_WIN32)
550 CreateConsole();
551#endif
552 if (!mgo.opt.empty()) SetDebugString(mgo.opt, ShowInfoI);
553 break;
554 }
555 case 'e':
556 /* Allow for '-e' before or after '-g'. */
557 switch (_switch_mode) {
561 default: break;
562 }
563 break;
564 case 'g':
565 if (!mgo.opt.empty()) {
566 _file_to_saveload.name = mgo.opt;
567
568 std::string extension = FS2OTTD(std::filesystem::path(OTTD2FS(_file_to_saveload.name)).extension().native());
570 if (ft == FIOS_TYPE_INVALID) {
572 }
573 if (ft == FIOS_TYPE_INVALID) {
574 std::tie(ft, _) = FiosGetHeightmapListCallback(SaveLoadOperation::Load, _file_to_saveload.name, extension);
575 }
576
577 /* Allow for '-e' before or after '-g'. */
578 switch (ft.abstract) {
582 default: break;
583 }
584
586 break;
587 }
588
590 /* Give a random map if no seed has been given */
591 if (scanner->generation_seed == GENERATE_NEW_SEED) {
592 scanner->generation_seed = InteractiveRandom();
593 }
594 break;
595 case 'q': {
596 DeterminePaths(arguments[0], only_local_path);
597 if (mgo.opt.empty()) {
598 return 1;
599 }
600
601 std::string extension = FS2OTTD(std::filesystem::path(OTTD2FS(mgo.opt)).extension().native());
602 auto [_, title] = FiosGetSavegameListCallback(SaveLoadOperation::Load, mgo.opt, extension);
603
604 _load_check_data.Clear();
606 if (res != SaveLoadResult::Ok || _load_check_data.HasErrors()) {
607 fmt::print(stderr, "Failed to open savegame\n");
608 if (_load_check_data.HasErrors()) {
609 InitializeLanguagePacks(); // A language pack is needed for GetString()
610 fmt::print(stderr, "{}\n", GetString(_load_check_data.error, _load_check_data.error_msg));
611 }
612 return 1;
613 }
614
615 WriteSavegameInfo(title);
616 return 0;
617 }
618 case 'Q': {
619 extern int _skip_all_newgrf_scanning;
621 break;
622 }
623 case 'G':
624 if (auto value = ParseInteger(mgo.opt); value.has_value()) {
625 scanner->generation_seed = *value;
626 } else {
627 fmt::print(stderr, "Invalid generation seed: {}\n", mgo.opt);
628 }
629 break;
630 case 'c': _config_file = mgo.opt; break;
631 case 'x': scanner->save_config = false; break;
632 case 'X': only_local_path = true; break;
633 case 'h': break; // handled below
634 }
635 if (i == 'h' || i == -2) break;
636 }
637
638 if (i == 'h' || i == -2 || !mgo.arguments.empty()) {
639 /* Either the user typed '-h', they made an error, or they added unrecognized command line arguments.
640 * In all cases, print the help, and exit.
641 *
642 * The next two functions are needed to list the graphics sets. We can't do them earlier
643 * because then we cannot show it on the debug console as that hasn't been configured yet. */
644 DeterminePaths(arguments[0], only_local_path);
649 ShowHelp();
650
651 /* Return zero when asked to print help, and 1 for all other cases. */
652 if (i == 'h') return 0;
653 return 1;
654 }
655
656 DeterminePaths(arguments[0], only_local_path);
658
659 if (dedicated) Debug(Facility::Net, Severity::Notice, "Starting dedicated server, version {}", _openttd_revision);
660 if (_dedicated_forks && !dedicated) _dedicated_forks = false;
661
662#if defined(UNIX)
663 /* We must fork here, or we'll end up without some resources we need (like sockets) */
664 if (_dedicated_forks) DedicatedFork();
665#endif
666
667 LoadFromConfig(true);
668
669 if (resolution.width != 0) _cur_resolution = resolution;
670
671 /* Limit width times height times bytes per pixel to fit a 32 bit
672 * integer, This way all internal drawing routines work correctly.
673 * A resolution that has one component as 0 is treated as a marker to
674 * auto-detect a good window size. */
675 _cur_resolution.width = std::min(_cur_resolution.width, UINT16_MAX / 2u);
676 _cur_resolution.height = std::min(_cur_resolution.height, UINT16_MAX / 2u);
677
678 /* Assume the cursor starts within the game as not all video drivers
679 * get an event that the cursor is within the window when it is opened.
680 * Saying the cursor is there makes no visible difference as it would
681 * just be out of the bounds of the window. */
682 _cursor.in_window = true;
683
684 /* enumerate language files */
686
687 /* Initialize the font cache */
689
690 /* This must be done early, since functions use the SetWindowDirty* calls */
692
694 bool valid_graphics_set;
695 if (!graphics_set.empty()) {
696 valid_graphics_set = BaseGraphics::SetSetByName(graphics_set);
697 } else if (BaseGraphics::ini_data.shortname != 0) {
698 graphics_set = BaseGraphics::ini_data.name;
699 valid_graphics_set = BaseGraphics::SetSetByShortname(BaseGraphics::ini_data.shortname);
700 if (valid_graphics_set && !BaseGraphics::ini_data.extra_params.empty()) {
702 if (extra_cfg.IsCompatible(BaseGraphics::ini_data.extra_version)) {
703 extra_cfg.SetParams(BaseGraphics::ini_data.extra_params);
704 }
705 }
706 } else if (!BaseGraphics::ini_data.name.empty()) {
707 graphics_set = BaseGraphics::ini_data.name;
708 valid_graphics_set = BaseGraphics::SetSetByName(BaseGraphics::ini_data.name);
709 } else {
710 valid_graphics_set = true;
711 BaseGraphics::SetSet(nullptr); // ignore error, continue to bootstrap GUI
712 }
713 if (!valid_graphics_set) {
714 BaseGraphics::SetSet(nullptr);
715
716 ErrorMessageData msg(GetEncodedString(STR_CONFIG_ERROR), GetEncodedString(STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND, graphics_set));
718 }
719
720 /* Initialize game palette */
721 GfxInitPalettes();
722
723 Debug(Facility::Misc, Severity::Error, "Loading blitter...");
724 if (blitter.empty() && !_ini_blitter.empty()) blitter = _ini_blitter;
725 _blitter_autodetected = blitter.empty();
726 /* Activate the initial blitter.
727 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
728 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
729 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
730 * - Use 8bpp blitter otherwise.
731 */
734 BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
735 if (BlitterFactory::SelectBlitter(blitter) == nullptr) {
736 blitter.empty() ?
737 UserError("Failed to autoprobe blitter") :
738 UserError("Failed to select requested blitter '{}'; does it exist?", blitter);
739 }
740 }
741
742 if (videodriver.empty() && !_ini_videodriver.empty()) videodriver = _ini_videodriver;
744
746
747 /* Initialize the zoom level of the screen to normal */
748 _screen.zoom = ZoomLevel::Min;
749
750 /* The video driver is now selected, now initialise GUI zoom */
752
754 NetworkStartUp(); // initialize network-core
755
756 if (!HandleBootstrap()) {
757 ShutdownGame();
758 return 0;
759 }
760
762
764 if (sounds_set.empty() && !BaseSounds::ini_set.empty()) sounds_set = BaseSounds::ini_set;
765 if (!BaseSounds::SetSetByName(sounds_set)) {
766 if (sounds_set.empty() || !BaseSounds::SetSet({})) {
767 UserError("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
768 } else {
769 ErrorMessageData msg(GetEncodedString(STR_CONFIG_ERROR), GetEncodedString(STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND, sounds_set));
771 }
772 }
773
775 if (music_set.empty() && !BaseMusic::ini_set.empty()) music_set = BaseMusic::ini_set;
776 if (!BaseMusic::SetSetByName(music_set)) {
777 if (music_set.empty() || !BaseMusic::SetSet({})) {
778 UserError("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
779 } else {
780 ErrorMessageData msg(GetEncodedString(STR_CONFIG_ERROR), GetEncodedString(STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND, music_set));
782 }
783 }
784
785 if (sounddriver.empty() && !_ini_sounddriver.empty()) sounddriver = _ini_sounddriver;
787
788 if (musicdriver.empty() && !_ini_musicdriver.empty()) musicdriver = _ini_musicdriver;
790
791 GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
792 LoadIntroGame(false);
793
794 /* ScanNewGRFFiles now has control over the scanner. */
795 RequestNewGRFScan(scanner.release());
796
798
799 PostMainLoop();
800 return 0;
801}
802
803void HandleExitGameRequest()
804{
805 if (_game_mode == GameMode::Menu || _game_mode == GameMode::Bootstrap) { // do not ask to quit on the main screen
806 _exit_game = true;
807 } else if (_settings_client.gui.autosave_on_exit) {
808 DoExitSave();
810 _exit_game = true;
811 } else {
812 AskExitGame();
813 }
814}
815
819static void OnStartScenario()
820{
821 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
823
824 /* Make sure all industries were built "this year", to avoid too early closures. (#9918) */
825 for (Industry *i : Industry::Iterate()) {
826 i->last_prod_year = TimerGameEconomy::year;
827 }
828}
829
834static void OnStartGame(bool dedicated_server)
835{
836 /* Update the local company for a loaded game. It is either the first available company
837 * or in the case of a dedicated server, a spectator */
838 SetLocalCompany(dedicated_server ? COMPANY_SPECTATOR : GetFirstPlayableCompanyID(), true);
839
841
842 /* Execute the game-start script */
843 IConsoleCmdExec("exec scripts/game_start.scr 0");
844}
845
846static void MakeNewGameDone()
847{
848 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
849
850 /* In a dedicated server, the server does not play */
851 if (!VideoDriver::GetInstance()->HasGUI()) {
852 OnStartGame(true);
853 if (_settings_client.gui.pause_on_newgame) Command<Commands::Pause>::Post(PauseMode::Normal, true);
854 return;
855 }
856
857 /* Create a single company */
858 DoStartupNewCompany(false);
859
860 Company *c = Company::Get(CompanyID::Begin());
861 c->settings = _settings_client.company;
862
863 /* Overwrite colour from settings if needed
864 * Colours::End corresponds to Random colour */
865
866 if (_settings_client.gui.starting_colour != Colours::End) {
867 Command<Commands::SetCompanyColour>::Post(LiveryScheme::Default, true, _settings_client.gui.starting_colour);
868 }
869
870 if (_settings_client.gui.starting_colour_secondary != Colours::End && _loaded_newgrf_features.used_liveries.Test(LiveryScheme::Default)) {
871 Command<Commands::SetCompanyColour>::Post(LiveryScheme::Default, false, _settings_client.gui.starting_colour_secondary);
872 }
873
874 OnStartGame(false);
875
877
878 if (_settings_client.gui.pause_on_newgame) Command<Commands::Pause>::Post(PauseMode::Normal, true);
879
880 CheckEngines();
883}
884
885static void MakeNewGame(bool from_heightmap, bool reset_settings)
886{
887 _game_mode = GameMode::Normal;
888 if (!from_heightmap) {
889 /* "reload" command needs to know what mode we were in. */
890 _file_to_saveload.SetMode(FIOS_TYPE_INVALID, SaveLoadOperation::Invalid);
891 }
892
893 ResetGRFConfig(true);
894
895 GenerateWorldSetCallback(&MakeNewGameDone);
896 GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
897}
898
899static void MakeNewEditorWorldDone()
900{
902}
903
904static void MakeNewEditorWorld()
905{
906 _game_mode = GameMode::Editor;
907 /* "reload" command needs to know what mode we were in. */
908 _file_to_saveload.SetMode(FIOS_TYPE_INVALID, SaveLoadOperation::Invalid);
909
910 ResetGRFConfig(true);
911
912 GenerateWorldSetCallback(&MakeNewEditorWorldDone);
913 GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
914}
915
928bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, std::shared_ptr<LoadFilter> lf = nullptr)
929{
930 assert(fop == SaveLoadOperation::Load);
931 assert(dft == DetailedFileType::GameFile || (lf == nullptr && dft == DetailedFileType::OldGameFile));
932 GameMode ogm = _game_mode;
933
934 _game_mode = newgm;
935
936 SaveLoadResult result = (lf == nullptr) ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(std::move(lf));
937 if (result == SaveLoadResult::Ok) return true;
938
939 if (_network_dedicated && ogm == GameMode::Menu) {
940 /*
941 * If we are a dedicated server *and* we just were in the menu, then we
942 * are loading the first savegame. If that fails, not starting the
943 * server is a better reaction than starting the server with a newly
944 * generated map as it is quite likely to be started from a script.
945 */
946 Debug(Facility::Net, Severity::Critical, "Loading requested map failed; closing server.");
947 _exit_game = true;
948 return false;
949 }
950
951 if (result != SaveLoadResult::ReInit) {
952 _game_mode = ogm;
953 return false;
954 }
955
956 if (_network_dedicated) {
957 /*
958 * If we are a dedicated server, have already loaded/started a game,
959 * and then loading the savegame fails in a manner that we need to
960 * reinitialize everything. We must not fall back into the menu mode
961 * with the intro game, as that is unjoinable by clients. So there is
962 * nothing else to do than start a new game, as it might have failed
963 * trying to reload the originally loaded savegame/scenario.
964 */
965 Debug(Facility::Net, Severity::Critical, "Loading game failed, so a new (random) game will be started");
966 MakeNewGame(false, true);
967 return false;
968 }
969
970 if (_network_server) {
971 /* We can't load the intro game as server, so disconnect first. */
973 }
974
975 switch (ogm) {
976 default:
977 case GameMode::Menu: LoadIntroGame(); break;
978 case GameMode::Editor: MakeNewEditorWorld(); break;
979 }
980 return false;
981}
982
983static void UpdateSocialIntegration(GameMode game_mode)
984{
985 switch (game_mode) {
987 case GameMode::Menu:
989 break;
990
991 case GameMode::Normal:
992 if (_networking) {
994 } else {
996 }
997 break;
998
999 case GameMode::Editor:
1001 break;
1002 }
1003}
1004
1005void SwitchToMode(SwitchMode new_mode)
1006{
1007 /* If we are saving something, the network stays in its current state */
1008 if (new_mode != SwitchMode::SaveGame) {
1009 /* If the network is active, make it not-active */
1010 if (_networking) {
1011 if (_network_server && (new_mode == SwitchMode::LoadGame || new_mode == SwitchMode::NewGame || new_mode == SwitchMode::RestartGame)) {
1012 NetworkReboot();
1013 } else {
1015 }
1016 }
1017
1018 /* If we are a server, we restart the server */
1019 if (_is_network_server) {
1020 /* But not if we are going to the menu */
1021 if (new_mode != SwitchMode::Menu) {
1022 /* check if we should reload the config */
1023 if (_settings_client.network.reload_cfg) {
1025 MakeNewgameSettingsLive();
1026 ResetGRFConfig(false);
1027 }
1029 } else {
1030 /* This client no longer wants to be a network-server */
1031 _is_network_server = false;
1032 }
1033 }
1034 }
1035
1036 /* Make sure all AI controllers are gone at quitting game */
1037 if (new_mode != SwitchMode::SaveGame) AI::KillAll();
1038
1039 /* When we change mode, reset the autosave. */
1040 if (new_mode != SwitchMode::SaveGame) ChangeAutosaveFrequency(true);
1041
1042 /* Transmit the survey if we were in normal-mode and not saving. It always means we leaving the current game. */
1043 if (_game_mode == GameMode::Normal && new_mode != SwitchMode::SaveGame) _survey.Transmit(NetworkSurveyHandler::Reason::Leave);
1044
1045 /* Keep track when we last switch mode. Used for survey, to know how long someone was in a game. */
1046 if (new_mode != SwitchMode::SaveGame) {
1047 _game_session_stats.start_time = std::chrono::steady_clock::now();
1048 _game_session_stats.savegame_size = std::nullopt;
1049 }
1050
1051 switch (new_mode) {
1052 case SwitchMode::Editor: // Switch to scenario editor
1053 MakeNewEditorWorld();
1055
1056 UpdateSocialIntegration(GameMode::Editor);
1057 break;
1058
1059 case SwitchMode::ReloadGame: // Reload with what-ever started the game
1061 /* Reload current savegame/scenario */
1063 SwitchToMode(_switch_mode);
1064 break;
1065 } else if (_file_to_saveload.ftype.abstract == AbstractFileType::Heightmap) {
1066 /* Restart current heightmap */
1068 SwitchToMode(_switch_mode);
1069 break;
1070 }
1071
1072 MakeNewGame(false, new_mode == SwitchMode::NewGame);
1074
1075 UpdateSocialIntegration(GameMode::Normal);
1076 break;
1077
1078 case SwitchMode::RestartGame: // Restart --> 'Random game' with current settings
1079 case SwitchMode::NewGame: // New Game --> 'Random game'
1080 MakeNewGame(false, new_mode == SwitchMode::NewGame);
1082
1083 UpdateSocialIntegration(GameMode::Normal);
1084 break;
1085
1086 case SwitchMode::LoadGame: { // Load game, Play Scenario
1087 ResetGRFConfig(true);
1089
1092 } else {
1093 if (_file_to_saveload.ftype.abstract == AbstractFileType::Scenario) {
1095 }
1097 /* Decrease pause counter (was increased from opening load dialog) */
1098 Command<Commands::Pause>::Post(PauseMode::SaveLoad, false);
1099 }
1100
1101 UpdateSocialIntegration(GameMode::Normal);
1102 break;
1103 }
1104
1105 case SwitchMode::RestartHeightmap: // Load a heightmap and start a new game from it with current settings
1106 case SwitchMode::StartHeightmap: // Load a heightmap and start a new game from it
1107 MakeNewGame(true, new_mode == SwitchMode::StartHeightmap);
1109
1110 UpdateSocialIntegration(GameMode::Normal);
1111 break;
1112
1113 case SwitchMode::LoadHeightmap: // Load heightmap from scenario editor
1115
1116 _game_mode = GameMode::Editor;
1117
1118 GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1121
1122 UpdateSocialIntegration(GameMode::Editor);
1123 break;
1124
1125 case SwitchMode::LoadScenario: { // Load scenario from scenario editor
1129 _settings_newgame.game_creation.starting_year = TimerGameCalendar::year;
1130 /* Cancel the saveload pausing */
1131 Command<Commands::Pause>::Post(PauseMode::SaveLoad, false);
1132 } else {
1134 }
1135
1136 UpdateSocialIntegration(GameMode::Editor);
1137 break;
1138 }
1139
1140 case SwitchMode::JoinGame: // Join a multiplayer game
1141 LoadIntroGame();
1143
1145 break;
1146
1147 case SwitchMode::Menu: // Switch to game intro menu
1148 LoadIntroGame();
1149 if (BaseSounds::ini_set.empty() && BaseSounds::GetUsedSet()->fallback && SoundDriver::GetInstance()->HasOutput()) {
1150 ShowErrorMessage(GetEncodedString(STR_WARNING_FALLBACK_SOUNDSET), {}, WarningLevel::Critical);
1152 }
1153 if (_settings_client.network.participate_survey == ParticipateSurvey::Ask) {
1154 /* No matter how often you go back to the main menu, only ask the first time. */
1155 static bool asked_once = false;
1156 if (!asked_once) {
1157 asked_once = true;
1159 }
1160 }
1161
1162 UpdateSocialIntegration(GameMode::Menu);
1163 break;
1164
1165 case SwitchMode::SaveGame: // Save game.
1166 /* Make network saved games on pause compatible to singleplayer mode */
1169 } else {
1170 CloseWindowById(WindowClass::SaveLoad, 0);
1171 }
1172 break;
1173
1174 case SwitchMode::SaveHeightmap: // Save heightmap.
1176 CloseWindowById(WindowClass::SaveLoad, 0);
1177 break;
1178
1179 case SwitchMode::GenerateRandomLand: // Generate random land within scenario editor
1181 GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1182 /* XXX: set date */
1184 break;
1185
1186 default: NOT_REACHED();
1187 }
1188}
1189
1190
1191
1198{
1199 if (!_networking || _network_server) {
1201 }
1202
1203 /* Don't execute the state loop during pause or when modal windows are open. */
1204 if (_pause_mode.Any() || HasModalProgress()) {
1212
1214#ifndef DEBUG_DUMP_COMMANDS
1215 if (_game_mode == GameMode::Normal) Game::GameLoop();
1216#endif
1217 return;
1218 }
1219
1222
1223 if (_game_mode == GameMode::Editor) {
1225 RunTileLoop();
1226 CallVehicleTicks();
1227 CallLandscapeTick();
1230
1232 NewsLoop();
1233 } else {
1235 /* Save the desync savegame if needed. */
1236 std::string name = fmt::format("dmp_cmds_{:08x}_{:08x}.sav", _settings_game.game_creation.generation_seed, TimerGameEconomy::date);
1238 }
1239
1240 CheckCaches();
1241
1242 /* All these actions has to be done from OWNER_NONE
1243 * for multiplayer compatibility */
1245
1250 }
1253 RunTileLoop();
1254 CallVehicleTicks();
1255 CallLandscapeTick();
1257
1258#ifndef DEBUG_DUMP_COMMANDS
1259 {
1261 AI::GameLoop();
1263 }
1264#endif
1266
1268 NewsLoop();
1269 }
1270
1271 assert(IsLocalCompany());
1272}
1273
1276{
1277 /* We reset the command-during-pause mode here, so we don't continue
1278 * to make auto-saves when nothing more is changing. */
1280
1281 _do_autosave = true;
1282 SetWindowDirty(WindowClass::Statusbar, 0);
1283
1284 static FiosNumberedSaveName _autosave_ctr("autosave");
1285 DoAutoOrNetsave(_autosave_ctr);
1286
1287 _do_autosave = false;
1288 SetWindowDirty(WindowClass::Statusbar, 0);
1289});
1290
1301{
1302 _autosave_interval.SetInterval({std::chrono::minutes(_settings_client.gui.autosave_interval), TimerGameRealtime::Trigger::Autosave}, reset);
1303}
1304
1314{
1315 if (_request_newgrf_scan) return false;
1316
1317 _request_newgrf_scan = true;
1318 _request_newgrf_scan_callback = callback;
1319 return true;
1320}
1321
1322void GameLoop()
1323{
1324 if (_game_mode == GameMode::Bootstrap) {
1325 /* Check for UDP stuff */
1327 return;
1328 }
1329
1330 if (_request_newgrf_scan) {
1331 ScanNewGRFFiles(_request_newgrf_scan_callback);
1332 _request_newgrf_scan = false;
1333 _request_newgrf_scan_callback = nullptr;
1334 /* In case someone closed the game during our scan, don't do anything else. */
1335 if (_exit_game) return;
1336 }
1337
1339
1340 if (_game_mode == GameMode::Normal) {
1341 static auto last_time = std::chrono::steady_clock::now();
1342 auto now = std::chrono::steady_clock::now();
1343 auto delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_time);
1344 if (delta_ms.count() != 0) {
1346 last_time = now;
1347 }
1348 }
1349
1350 /* switch game mode? */
1352 SwitchToMode(_switch_mode);
1354 if (_exit_game) return;
1355 }
1356
1357 IncreaseSpriteLRU();
1358
1359 /* Check for UDP stuff */
1361
1363
1364 if (_networking && !HasModalProgress()) {
1365 /* Multiplayer */
1367 } else {
1368 if (_network_reconnect > 0 && --_network_reconnect == 0) {
1369 /* This means that we want to reconnect to the last host
1370 * We do this here, because it means that the network is really closed */
1372 }
1373 /* Singleplayer */
1374 StateGameLoop();
1375 }
1376
1377 if (_pause_mode.None() && _display_opt.Test(DisplayOption::FullAnimation)) DoPaletteAnimations();
1378
1380 MusicLoop();
1382}
Base functions for all AIs.
AIConfig stores the configuration settings of every AI.
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 graphics data.
@ BLT_8BPP
Base set has 8 bpp sprites only.
Generic functions for replacing base music data.
Generic functions for replacing base sounds data.
static void Uninitialize(bool keepConfig)
Uninitialize the AI system.
Definition ai_core.cpp:175
static void Initialize()
Initialize the AI system.
Definition ai_core.cpp:161
static void GetConsoleList(std::back_insert_iterator< std::string > &output_iterator, bool newest_only)
Get the list of registered scripts to print on the console.
Definition ai_core.cpp:282
static void GameLoop()
Called every game-tick to let AIs do something.
Definition ai_core.cpp:82
static void KillAll()
Kill any and all AIs we manage.
Definition ai_core.cpp:151
static const GraphicsSet * GetUsedSet()
static bool SetSetByShortname(uint32_t shortname)
static void GetSetsList(std::back_insert_iterator< std::string > &output_iterator)
static bool SetSetByName(const std::string &name)
static bool SetSet(const GraphicsSet *set)
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:148
static Blitter * SelectBlitter(std::string_view name)
Find the requested blitter and return its class.
Definition factory.hpp:98
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:125
static void SelectDriver(const std::string &name, Driver::Type type)
Find the requested driver and return its class.
Definition driver.cpp:94
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
virtual void Stop()=0
Stop this driver.
@ Video
A video driver.
Definition driver.h:43
@ Music
A music driver, needs to be before sound to properly shut down extmidi forked music players.
Definition driver.h:41
@ Sound
A sound driver.
Definition driver.h:42
The data of the error message.
Definition error.h:29
static void UninitializeFontCaches()
Free everything allocated w.r.t.
static void LoadFontCaches(FontSizes fontsizes)
(Re)initialize the font cache related things, i.e.
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)
Get the list of registered scripts to print on the console.
static void Uninitialize(bool keepConfig)
Uninitialize the Game system.
Definition game_core.cpp:97
static void Initialize()
Initialize the Game system.
Definition game_core.cpp:55
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
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.
@ Leave
User is leaving the game (but not exiting the application).
@ Exit
User is exiting the application.
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.
Parse data from a string / buffer.
std::optional< T > TryReadIntegerBase(int base, bool clamp=false)
Try to read and parse an integer in number 'base', and then advance the reader.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
bool ReadIf(std::string_view str)
Check whether the next data matches 'str', and skip it.
@ Scenario
Scan for scenarios and heightmaps.
Definition fileio_func.h:67
@ Baseset
Scan for base sets.
Definition fileio_func.h:64
uint DoScan(Subdirectory sd)
Perform the scanning of a particular subdirectory.
Definition fileio.cpp:382
static Year year
Current year, starting at 0.
static constexpr TimerGame< struct Calendar >::Year 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.
StrongType::Typedef< int32_t, struct YearTag< struct Calendar >, StrongType::Compare, StrongType::Integer > Year
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.
virtual void ClaimMousePointer()
Claim the exclusive rights for the mouse pointer.
Functions related to commands.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
void SetLocalCompany(CompanyID new_company, bool switching_game)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
void UpdateLandscapingLimits()
Update the landscaping limits per company.
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(std::string_view command_string, const uint recurse_count)
Execute a given command passed to us.
Definition console.cpp:272
Console functions used outside of the console code.
Functions to be called to log a crash.
void SetDebugString(std::string_view s, SetDebugStringErrorFunc error_func)
Set debugging levels by parsing the text in s.
Definition debug.cpp:121
void DumpDebugFacilityNames(std::back_insert_iterator< std::string > &output_iterator)
Dump the available debug facility names in the help text.
Definition debug.cpp:64
void DebugSendRemoteMessages()
Send the queued Debug messages to either NetworkAdminConsole or IConsolePrint from the GameLoop threa...
Definition debug.cpp:206
bool IsVisibleSeverity(Facility facility, Severity severity)
Test if debug severity is visible for the given facility.
Definition debug.h:24
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Desync
Desync message facility.
Definition debug_type.h:41
@ Net
Net message facility.
Definition debug_type.h:33
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Notice
Notice.
Definition debug_type.h:18
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
bool _dedicated_forks
Whether a fork has been done.
std::string _ini_videodriver
The video driver a stored in the configuration file.
Definition driver.cpp:27
std::string _ini_musicdriver
The music driver a stored in the configuration file.
Definition driver.cpp:34
Dimension _cur_resolution
The current resolution.
Definition driver.cpp:29
std::string _ini_sounddriver
The sound driver a stored in the configuration file.
Definition driver.cpp:32
void SettingsDisableElrail(int32_t new_value)
Callback for changes to the electrified rails setting.
Definition elrail.cpp:580
Header file for electrified rail specific functions.
void CheckEngines()
Check for engines that have an appropriate availability.
Definition engine.cpp:1351
Base class for engines.
Functions related to engines.
Functions related to errors.
void ScheduleErrorMessage(ErrorList &datas)
Schedule a list of errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
Definition error.h:25
@ Error
Errors (eg. saving/loading failed).
Definition error.h:24
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, 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:37
std::string _ini_blitter
The blitter as stored in the configuration file.
Definition driver.cpp:36
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:932
std::string _config_file
Configuration file of OpenTTD.
Definition settings.cpp:64
SaveLoadOperation
Operation performed on the file.
Definition fileio_type.h:51
@ Check
Load file for checking and/or preview.
Definition fileio_type.h:52
@ Invalid
Unknown file operation.
Definition fileio_type.h:56
@ Save
File is being saved.
Definition fileio_type.h:54
@ Load
File is being loaded.
Definition fileio_type.h:53
DetailedFileType
Kinds of files in each AbstractFileType.
Definition fileio_type.h:27
@ OldGameFile
Old save game or scenario file.
Definition fileio_type.h:29
@ GameFile
Save game or scenario file.
Definition fileio_type.h:30
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition fileio_type.h:87
@ Autosave
Subdirectory of save for autosaves.
Definition fileio_type.h:90
@ None
A path without any base directory.
@ Baseset
Subdirectory for all base data (base sets, intro game).
Definition fileio_type.h:95
@ Save
Base directory for all savegames.
Definition fileio_type.h:89
@ Savegame
old or new savegame
Definition fileio_type.h:18
@ Scenario
old or new scenario
Definition fileio_type.h:19
@ Heightmap
heightmap file
Definition fileio_type.h:20
std::tuple< FiosType, std::string > FiosGetScenarioListCallback(SaveLoadOperation fop, std::string_view file, std::string_view ext)
Callback for FiosGetFileList.
Definition fios.cpp:461
std::tuple< FiosType, std::string > FiosGetSavegameListCallback(SaveLoadOperation fop, std::string_view file, std::string_view ext)
Callback for FiosGetFileList.
Definition fios.cpp:412
Declarations for savegames operations.
LoadCheckData _load_check_data
Data loaded from save during SL_LOAD_CHECK.
Definition fios_gui.cpp:42
Functions to read fonts from files and cache them.
Types for recording game performance data.
@ GameLoopLandscape
Time spent processing other world features.
@ GameLoopRoadVehicles
Time spend processing road vehicles.
@ GameLoop
Speed of gameloop processing.
@ GameLoopShips
Time spent processing ships.
@ AllScripts
Sum of all GS/AI scripts.
@ GameLoopAircraft
Time spent processing aircraft.
@ GameLoopTrains
Time spent processing trains.
@ GameLoopEconomy
Time spent processing cargo movement.
Base functions for all Games.
GameConfig stores the configuration settings of every Game.
SaveLoadVersion _sl_version
the major savegame version identifier
Definition saveload.cpp:84
Gamelog _gamelog
Gamelog instance.
Definition gamelog.cpp:30
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:23
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
Definition genworld.h:30
@ GWM_EMPTY
Generate an empty map (sea-level).
Definition genworld.h:28
@ GWM_RANDOM
Generate a random map for SE.
Definition genworld.h:29
@ GWM_NEWGAME
Generate a map for a new game.
Definition genworld.h:27
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:47
void UpdateGUIZoom()
Resolve GUI zoom level, if auto-suggestion is requested.
Definition gfx.cpp:1836
Support8bpp _support8bpp
State of the support for 8bpp graphics.
Definition gfx.cpp:38
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:46
SwitchMode _switch_mode
The next mainloop command.
Definition gfx.cpp:45
@ None
No support for 8bpp by OS or hardware, force 32bpp blitters.
Definition gfx_type.h:428
@ End
End-of-array marker.
Definition gfx_type.h:301
constexpr FontSizes FONTSIZES_REQUIRED
Mask of font sizes required to be present.
Definition gfx_type.h:264
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
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:334
void SaveHotkeysToConfig()
Save the hotkeys to the config file.
Definition hotkeys.cpp:340
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...
Functions related to OTTD's landscape.
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.
@ Default
Default scheme.
Definition livery.h:24
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
Definition main_gui.cpp:549
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:1319
bool _is_network_server
Does this client wants to be a network-server?
Definition network.cpp:67
void NetworkClientJoinGame()
Actually perform the joining to the server.
Definition network.cpp:838
void NetworkOnGameStart()
Perform tasks when the server is started.
Definition network.cpp:975
bool _network_available
is network mode available?
Definition network.cpp:65
bool NetworkServerStart()
Run everything related to the network when starting a server.
Definition network.cpp:919
uint8_t _network_reconnect
Reconnect timeout.
Definition network.cpp:70
bool _networking
are we in networking mode?
Definition network.cpp:63
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:66
void NetworkGameLoop()
The main loop called from ttd.c.
Definition network.cpp:1128
void NetworkReboot()
The server is rebooting... The only difference with NetworkDisconnect, is the packets that is sent.
Definition network.cpp:1008
void NetworkDisconnect(bool close_admins)
We want to disconnect from the host/clients.
Definition network.cpp:1031
bool _network_server
network-server is active
Definition network.cpp:64
void NetworkBackgroundLoop()
We have to do some (simple) background stuff that runs normally, even when we are not in multiplayer.
Definition network.cpp:1112
StringList _network_bind_list
The addresses to bind on.
Definition network.cpp:71
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:805
void NetworkShutDown()
This shuts the network down.
Definition network.cpp:1337
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:527
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.
NetworkSurveyHandler _survey
The handler for sending surveys for statistics.
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:75
Base for the NewGRF implementation.
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.
void UpdateNewGRFConfigPalette()
Update the palettes of the graphics from the config file.
@ 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:129
static IntervalTimer< TimerGameRealtime > _autosave_interval({std::chrono::milliseconds::zero(), TimerGameRealtime::Trigger::Autosave}, [](auto) { _pause_mode.Reset(PauseMode::CommandDuringPause);_do_autosave=true;SetWindowDirty(WindowClass::Statusbar, 0);static FiosNumberedSaveName _autosave_ctr("autosave");DoAutoOrNetsave(_autosave_ctr);_do_autosave=false;SetWindowDirty(WindowClass::Statusbar, 0);})
Interval for regular autosaves.
int openttd_main(std::span< std::string_view > arguments)
Main entry point for this lovely game.
Definition openttd.cpp:486
static void OnStartScenario()
Triggers everything required to set up a saved scenario for a new game.
Definition openttd.cpp:819
Company * DoStartupNewCompany(bool is_ai, CompanyID company=CompanyID::Invalid())
Create a new company and sets all company variables default values.
static void OnStartGame(bool dedicated_server)
Triggers everything that should be triggered when starting a game.
Definition openttd.cpp:834
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:263
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:928
void ChangeAutosaveFrequency(bool reset)
Reset the interval of the autosave.
Definition openttd.cpp:1300
void ShowOSErrorBox(std::string_view buf, bool system)
Show an error message.
Definition macos.mm:62
void StateGameLoop()
State controlling game loop.
Definition openttd.cpp:1197
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:143
bool RequestNewGRFScan(NewGRFScanCallback *callback)
Request a new NewGRF scan.
Definition openttd.cpp:1313
static void ShutdownGame()
Uninitializes drivers, frees allocated memory, cleans pools, ... Generally, prepares the game for shu...
Definition openttd.cpp:283
static void LoadIntroGame(bool load_newgrfs=true)
Load the introduction game.
Definition openttd.cpp:311
static std::vector< OptionData > CreateOptions()
Create all the options that OpenTTD supports.
Definition openttd.cpp:463
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
Definition window.cpp:3407
void CheckCaches()
Check the validity of some of the caches.
bool HandleBootstrap()
Handle all procedures for bootstrapping OpenTTD without a base graphics set.
void OSOpenBrowser(const std::string &url)
Opens browser on MacOS.
Definition macos.mm:76
@ FullAnimation
Perform palette animation.
Definition openttd.h:49
@ Normal
A game normally paused.
Definition openttd.h:72
@ CommandDuringPause
A game paused, and a command executed during the pause; resets on autosave.
Definition openttd.h:79
@ SaveLoad
A game paused for saving/loading.
Definition openttd.h:73
GameMode
Mode which defines the state of the game.
Definition openttd.h:18
@ Editor
In the scenario editor.
Definition openttd.h:21
@ Bootstrap
In the content bootstrap process.
Definition openttd.h:22
@ Normal
Playing a game.
Definition openttd.h:20
@ Menu
In the main menu.
Definition openttd.h:19
SwitchMode
Mode which defines what mode we're switching to.
Definition openttd.h:26
@ LoadGame
Load game, Play Scenario.
Definition openttd.h:32
@ JoinGame
Join a network game.
Definition openttd.h:41
@ LoadScenario
Load scenario from scenario editor.
Definition openttd.h:37
@ StartHeightmap
Load a heightmap and start a new game from it.
Definition openttd.h:38
@ NewGame
New Game --> 'Random game'.
Definition openttd.h:28
@ Editor
Switch to scenario editor.
Definition openttd.h:31
@ GenerateRandomLand
Generate random land within scenario editor.
Definition openttd.h:36
@ None
Not switching game mode.
Definition openttd.h:27
@ ReloadGame
Reload the savegame / scenario / heightmap you started the game with.
Definition openttd.h:30
@ SaveGame
Save game.
Definition openttd.h:34
@ RestartHeightmap
Load a heightmap and start a new game from it with current settings.
Definition openttd.h:40
@ Menu
Switch to game intro menu.
Definition openttd.h:33
@ LoadHeightmap
Load heightmap from scenario editor.
Definition openttd.h:39
@ SaveHeightmap
Save heightmap.
Definition openttd.h:35
@ RestartGame
Restart --> 'Random game' with current settings.
Definition openttd.h:29
Functions related to modal progress.
bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition progress.h:17
void InitializeSignalGui()
Resets the signal GUI.
Functions/types etc.
Pseudo random number generator.
Declaration of OTTD revision dependent variables.
A number of safeguards to prevent using unsafe methods.
void ProcessAsyncSaveFinish()
Handle async save finishes.
Definition saveload.cpp:397
SaveLoadResult 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.
bool _do_autosave
are we doing an autosave at the moment?
Definition saveload.cpp:87
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:81
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit).
EncodedString GetSaveLoadErrorMessage()
Return the description of the error.
SaveLoadResult LoadWithFilter(std::shared_ptr< LoadFilter > reader)
Load the game using a (reader) filter.
Functions/types related to saving and loading games.
SaveLoadVersion
SaveLoad versions Previous savegame versions, the trunk revision where they were introduced and the r...
Definition saveload.h:35
Functions related to saving and loading games.
SaveLoadResult
Save or load result codes.
@ Ok
completed successfully
@ ReInit
error that was caught in the middle of updating game state, need to clear it. (can only happen during...
bool MakeHeightmapScreenshot(std::string_view 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:63
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition settings.cpp:62
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Functions related to setting/changing the settings.
Interface definitions for game to report/respond to social integration.
Base for all sound drivers.
Functions to cache sprites in memory.
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:76
Parse strings.
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
void CheckForMissingGlyphs(FontSizes fontsizes, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
Definition strings.cpp:2381
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
void InitializeLanguagePacks()
Make a list of the available language packs.
Definition strings.cpp:2250
Functions related to OTTD's strings.
std::string dedicated_host
Hostname for the dedicated server.
Definition openttd.cpp:363
TimerGameCalendar::Year startyear
The start year.
Definition openttd.cpp:361
void OnNewGRFsScanned() override
Called whenever the NewGRF scan completed.
Definition openttd.cpp:379
uint16_t dedicated_port
Port for the dedicated server.
Definition openttd.cpp:364
bool save_config
The save config setting.
Definition openttd.cpp:367
std::string connection_string
Information about the server to connect to.
Definition openttd.cpp:365
uint32_t generation_seed
Seed for the new game.
Definition openttd.cpp:362
std::string join_server_password
The password to join the server with.
Definition openttd.cpp:366
AfterNewGRFScan()
Create a new callback.
Definition openttd.cpp:372
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
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 settings
settings specific for each company
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
static bool ResetToCurrentNewGRFConfig()
Tries to reset the engine mapping to match the current NewGRF configuration.
Definition engine.cpp:622
A savegame name automatically numbered.
Definition fios.h:127
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.
Data storage for parsing command line options.
Definition getoptdata.h:29
std::string_view opt
Option value, if available (else empty).
Definition getoptdata.h:35
ArgumentSpan arguments
Remaining command line arguments.
Definition getoptdata.h:33
int GetOpt()
Find the next option.
GRFConfig & GetOrCreateExtraConfig() const
Return configuration for the extra GRF, or lazily create it.
Definition gfxinit.cpp:378
Defines the internal data of a functional industry.
Definition industry.h:64
static uint SizeX()
Get the size of the map along the X.
Definition map_func.h:262
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:271
Callback for NewGRF scanning.
static void Clean(PoolTypes)
Clean all pools of given type.
Definition pool_func.cpp:30
static Pool::IterateWrapper< Industry > Iterate(size_t from=0)
static Company * Get(auto index)
static void SaveToConfig()
Save all WindowDesc settings to _windows_file.
Definition window.cpp:182
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
Definition window.cpp:163
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.
DisplayOptions _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:939
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(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:389
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:373
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:1242
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition window.cpp:1941
void UnInitWindowSystem()
Close down the windowing system.
Definition window.cpp:1927
void InitWindowSystem()
(re)initialize the windowing system
Definition window.cpp:1905
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
Window functions not directly related to making/drawing windows.
@ Min
Minimum zoom level.
Definition zoom_type.h:23