Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / console_cmds.cpp
blob98a521861e7a06e4637b1f5102fbb4031a4076a0
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 */
8 /** @file console_cmds.cpp Implementation of the console hooks. */
10 #include "stdafx.h"
11 #include "console_internal.h"
12 #include "debug.h"
13 #include "engine_func.h"
14 #include "landscape.h"
15 #include "saveload/saveload.h"
16 #include "network/core/network_game_info.h"
17 #include "network/network.h"
18 #include "network/network_func.h"
19 #include "network/network_base.h"
20 #include "network/network_admin.h"
21 #include "network/network_client.h"
22 #include "command_func.h"
23 #include "settings_func.h"
24 #include "fios.h"
25 #include "fileio_func.h"
26 #include "fontcache.h"
27 #include "screenshot.h"
28 #include "genworld.h"
29 #include "strings_func.h"
30 #include "viewport_func.h"
31 #include "window_func.h"
32 #include "timer/timer_game_calendar.h"
33 #include "company_func.h"
34 #include "gamelog.h"
35 #include "ai/ai.hpp"
36 #include "ai/ai_config.hpp"
37 #include "newgrf.h"
38 #include "newgrf_profiling.h"
39 #include "console_func.h"
40 #include "engine_base.h"
41 #include "road.h"
42 #include "rail.h"
43 #include "game/game.hpp"
44 #include "table/strings.h"
45 #include "3rdparty/fmt/chrono.h"
46 #include "company_cmd.h"
47 #include "misc_cmd.h"
49 #include <sstream>
51 #include "safeguards.h"
53 /* scriptfile handling */
54 static uint _script_current_depth; ///< Depth of scripts running (used to abort execution when #ConReturn is encountered).
56 /** File list storage for the console, for caching the last 'ls' command. */
57 class ConsoleFileList : public FileList {
58 public:
59 ConsoleFileList(AbstractFileType abstract_filetype, bool show_dirs) : FileList(), abstract_filetype(abstract_filetype), show_dirs(show_dirs)
63 /** Declare the file storage cache as being invalid, also clears all stored files. */
64 void InvalidateFileList()
66 this->clear();
67 this->file_list_valid = false;
70 /**
71 * (Re-)validate the file storage cache. Only makes a change if the storage was invalid, or if \a force_reload.
72 * @param force_reload Always reload the file storage cache.
74 void ValidateFileList(bool force_reload = false)
76 if (force_reload || !this->file_list_valid) {
77 this->BuildFileList(this->abstract_filetype, SLO_LOAD, this->show_dirs);
78 this->file_list_valid = true;
82 AbstractFileType abstract_filetype; ///< The abstract file type to list.
83 bool show_dirs; ///< Whether to show directories in the file list.
84 bool file_list_valid = false; ///< If set, the file list is valid.
87 static ConsoleFileList _console_file_list_savegame{FT_SAVEGAME, true}; ///< File storage cache for savegames.
88 static ConsoleFileList _console_file_list_scenario{FT_SCENARIO, false}; ///< File storage cache for scenarios.
89 static ConsoleFileList _console_file_list_heightmap{FT_HEIGHTMAP, false}; ///< File storage cache for heightmaps.
91 /* console command defines */
92 #define DEF_CONSOLE_CMD(function) static bool function([[maybe_unused]] byte argc, [[maybe_unused]] char *argv[])
93 #define DEF_CONSOLE_HOOK(function) static ConsoleHookResult function(bool echo)
96 /****************
97 * command hooks
98 ****************/
101 * Check network availability and inform in console about failure of detection.
102 * @return Network availability.
104 static inline bool NetworkAvailable(bool echo)
106 if (!_network_available) {
107 if (echo) IConsolePrint(CC_ERROR, "You cannot use this command because there is no network available.");
108 return false;
110 return true;
114 * Check whether we are a server.
115 * @return Are we a server? True when yes, false otherwise.
117 DEF_CONSOLE_HOOK(ConHookServerOnly)
119 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
121 if (!_network_server) {
122 if (echo) IConsolePrint(CC_ERROR, "This command is only available to a network server.");
123 return CHR_DISALLOW;
125 return CHR_ALLOW;
129 * Check whether we are a client in a network game.
130 * @return Are we a client in a network game? True when yes, false otherwise.
132 DEF_CONSOLE_HOOK(ConHookClientOnly)
134 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
136 if (_network_server) {
137 if (echo) IConsolePrint(CC_ERROR, "This command is not available to a network server.");
138 return CHR_DISALLOW;
140 return CHR_ALLOW;
144 * Check whether we are in a multiplayer game.
145 * @return True when we are client or server in a network game.
147 DEF_CONSOLE_HOOK(ConHookNeedNetwork)
149 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
151 if (!_networking || (!_network_server && !MyClient::IsConnected())) {
152 if (echo) IConsolePrint(CC_ERROR, "Not connected. This command is only available in multiplayer.");
153 return CHR_DISALLOW;
155 return CHR_ALLOW;
159 * Check whether we are in singleplayer mode.
160 * @return True when no network is active.
162 DEF_CONSOLE_HOOK(ConHookNoNetwork)
164 if (_networking) {
165 if (echo) IConsolePrint(CC_ERROR, "This command is forbidden in multiplayer.");
166 return CHR_DISALLOW;
168 return CHR_ALLOW;
172 * Check if are either in singleplayer or a server.
173 * @return True iff we are either in singleplayer or a server.
175 DEF_CONSOLE_HOOK(ConHookServerOrNoNetwork)
177 if (_networking && !_network_server) {
178 if (echo) IConsolePrint(CC_ERROR, "This command is only available to a network server.");
179 return CHR_DISALLOW;
181 return CHR_ALLOW;
184 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool)
186 if (_settings_client.gui.newgrf_developer_tools) {
187 if (_game_mode == GM_MENU) {
188 if (echo) IConsolePrint(CC_ERROR, "This command is only available in-game and in the editor.");
189 return CHR_DISALLOW;
191 return ConHookNoNetwork(echo);
193 return CHR_HIDE;
197 * Reset status of all engines.
198 * @return Will always succeed.
200 DEF_CONSOLE_CMD(ConResetEngines)
202 if (argc == 0) {
203 IConsolePrint(CC_HELP, "Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'.");
204 return true;
207 StartupEngines();
208 return true;
212 * Reset status of the engine pool.
213 * @return Will always return true.
214 * @note Resetting the pool only succeeds when there are no vehicles ingame.
216 DEF_CONSOLE_CMD(ConResetEnginePool)
218 if (argc == 0) {
219 IConsolePrint(CC_HELP, "Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
220 return true;
223 if (_game_mode == GM_MENU) {
224 IConsolePrint(CC_ERROR, "This command is only available in-game and in the editor.");
225 return true;
228 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
229 IConsolePrint(CC_ERROR, "This can only be done when there are no vehicles in the game.");
230 return true;
233 return true;
236 #ifdef _DEBUG
238 * Reset a tile to bare land in debug mode.
239 * param tile number.
240 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
242 DEF_CONSOLE_CMD(ConResetTile)
244 if (argc == 0) {
245 IConsolePrint(CC_HELP, "Reset a tile to bare land. Usage: 'resettile <tile>'.");
246 IConsolePrint(CC_HELP, "Tile can be either decimal (34161) or hexadecimal (0x4a5B).");
247 return true;
250 if (argc == 2) {
251 uint32_t result;
252 if (GetArgumentInteger(&result, argv[1])) {
253 DoClearSquare((TileIndex)result);
254 return true;
258 return false;
260 #endif /* _DEBUG */
263 * Zoom map to given level.
264 * param level As defined by ZoomLevel and as limited by zoom_min/zoom_max from GUISettings.
265 * @return True when either console help was shown or a proper amount of parameters given.
267 DEF_CONSOLE_CMD(ConZoomToLevel)
269 switch (argc) {
270 case 0:
271 IConsolePrint(CC_HELP, "Set the current zoom level of the main viewport.");
272 IConsolePrint(CC_HELP, "Usage: 'zoomto <level>'.");
274 if (ZOOM_LVL_MIN < _settings_client.gui.zoom_min) {
275 IConsolePrint(CC_HELP, "The lowest zoom-in level allowed by current client settings is {}.", std::max(ZOOM_LVL_MIN, _settings_client.gui.zoom_min));
276 } else {
277 IConsolePrint(CC_HELP, "The lowest supported zoom-in level is {}.", std::max(ZOOM_LVL_MIN, _settings_client.gui.zoom_min));
280 if (_settings_client.gui.zoom_max < ZOOM_LVL_MAX) {
281 IConsolePrint(CC_HELP, "The highest zoom-out level allowed by current client settings is {}.", std::min(_settings_client.gui.zoom_max, ZOOM_LVL_MAX));
282 } else {
283 IConsolePrint(CC_HELP, "The highest supported zoom-out level is {}.", std::min(_settings_client.gui.zoom_max, ZOOM_LVL_MAX));
285 return true;
287 case 2: {
288 uint32_t level;
289 if (GetArgumentInteger(&level, argv[1])) {
290 /* In case ZOOM_LVL_MIN is more than 0, the next if statement needs to be amended.
291 * A simple check for less than ZOOM_LVL_MIN does not work here because we are
292 * reading an unsigned integer from the console, so just check for a '-' char. */
293 static_assert(ZOOM_LVL_MIN == 0);
294 if (argv[1][0] == '-') {
295 IConsolePrint(CC_ERROR, "Zoom-in levels below {} are not supported.", ZOOM_LVL_MIN);
296 } else if (level < _settings_client.gui.zoom_min) {
297 IConsolePrint(CC_ERROR, "Current client settings do not allow zooming in below level {}.", _settings_client.gui.zoom_min);
298 } else if (level > ZOOM_LVL_MAX) {
299 IConsolePrint(CC_ERROR, "Zoom-in levels above {} are not supported.", ZOOM_LVL_MAX);
300 } else if (level > _settings_client.gui.zoom_max) {
301 IConsolePrint(CC_ERROR, "Current client settings do not allow zooming out beyond level {}.", _settings_client.gui.zoom_max);
302 } else {
303 Window *w = GetMainWindow();
304 Viewport *vp = w->viewport;
305 while (vp->zoom > level) DoZoomInOutWindow(ZOOM_IN, w);
306 while (vp->zoom < level) DoZoomInOutWindow(ZOOM_OUT, w);
308 return true;
310 break;
314 return false;
318 * Scroll to a tile on the map.
319 * param x tile number or tile x coordinate.
320 * param y optional y coordinate.
321 * @note When only one argument is given it is interpreted as the tile number.
322 * When two arguments are given, they are interpreted as the tile's x
323 * and y coordinates.
324 * @return True when either console help was shown or a proper amount of parameters given.
326 DEF_CONSOLE_CMD(ConScrollToTile)
328 if (argc == 0) {
329 IConsolePrint(CC_HELP, "Center the screen on a given tile.");
330 IConsolePrint(CC_HELP, "Usage: 'scrollto [instant] <tile>' or 'scrollto [instant] <x> <y>'.");
331 IConsolePrint(CC_HELP, "Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
332 IConsolePrint(CC_HELP, "'instant' will immediately move and redraw viewport without smooth scrolling.");
333 return true;
335 if (argc < 2) return false;
337 uint32_t arg_index = 1;
338 bool instant = false;
339 if (strcmp(argv[arg_index], "instant") == 0) {
340 ++arg_index;
341 instant = true;
344 switch (argc - arg_index) {
345 case 1: {
346 uint32_t result;
347 if (GetArgumentInteger(&result, argv[arg_index])) {
348 if (result >= Map::Size()) {
349 IConsolePrint(CC_ERROR, "Tile does not exist.");
350 return true;
352 ScrollMainWindowToTile((TileIndex)result, instant);
353 return true;
355 break;
358 case 2: {
359 uint32_t x, y;
360 if (GetArgumentInteger(&x, argv[arg_index]) && GetArgumentInteger(&y, argv[arg_index + 1])) {
361 if (x >= Map::SizeX() || y >= Map::SizeY()) {
362 IConsolePrint(CC_ERROR, "Tile does not exist.");
363 return true;
365 ScrollMainWindowToTile(TileXY(x, y), instant);
366 return true;
368 break;
372 return false;
376 * Save the map to a file.
377 * param filename the filename to save the map to.
378 * @return True when help was displayed or the file attempted to be saved.
380 DEF_CONSOLE_CMD(ConSave)
382 if (argc == 0) {
383 IConsolePrint(CC_HELP, "Save the current game. Usage: 'save <filename>'.");
384 return true;
387 if (argc == 2) {
388 std::string filename = argv[1];
389 filename += ".sav";
390 IConsolePrint(CC_DEFAULT, "Saving map...");
392 if (SaveOrLoad(filename, SLO_SAVE, DFT_GAME_FILE, SAVE_DIR) != SL_OK) {
393 IConsolePrint(CC_ERROR, "Saving map failed.");
394 } else {
395 IConsolePrint(CC_INFO, "Map successfully saved to '{}'.", filename);
397 return true;
400 return false;
404 * Explicitly save the configuration.
405 * @return True.
407 DEF_CONSOLE_CMD(ConSaveConfig)
409 if (argc == 0) {
410 IConsolePrint(CC_HELP, "Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
411 IConsolePrint(CC_HELP, "It does not save the configuration of the current game to the configuration file.");
412 return true;
415 SaveToConfig();
416 IConsolePrint(CC_DEFAULT, "Saved config.");
417 return true;
420 DEF_CONSOLE_CMD(ConLoad)
422 if (argc == 0) {
423 IConsolePrint(CC_HELP, "Load a game by name or index. Usage: 'load <file | number>'.");
424 return true;
427 if (argc != 2) return false;
429 const char *file = argv[1];
430 _console_file_list_savegame.ValidateFileList();
431 const FiosItem *item = _console_file_list_savegame.FindItem(file);
432 if (item != nullptr) {
433 if (GetAbstractFileType(item->type) == FT_SAVEGAME) {
434 _switch_mode = SM_LOAD_GAME;
435 _file_to_saveload.Set(*item);
436 } else {
437 IConsolePrint(CC_ERROR, "'{}' is not a savegame.", file);
439 } else {
440 IConsolePrint(CC_ERROR, "'{}' cannot be found.", file);
443 return true;
446 DEF_CONSOLE_CMD(ConLoadScenario)
448 if (argc == 0) {
449 IConsolePrint(CC_HELP, "Load a scenario by name or index. Usage: 'load_scenario <file | number>'.");
450 return true;
453 if (argc != 2) return false;
455 const char *file = argv[1];
456 _console_file_list_scenario.ValidateFileList();
457 const FiosItem *item = _console_file_list_scenario.FindItem(file);
458 if (item != nullptr) {
459 if (GetAbstractFileType(item->type) == FT_SCENARIO) {
460 _switch_mode = SM_LOAD_GAME;
461 _file_to_saveload.Set(*item);
462 } else {
463 IConsolePrint(CC_ERROR, "'{}' is not a scenario.", file);
465 } else {
466 IConsolePrint(CC_ERROR, "'{}' cannot be found.", file);
469 return true;
472 DEF_CONSOLE_CMD(ConLoadHeightmap)
474 if (argc == 0) {
475 IConsolePrint(CC_HELP, "Load a heightmap by name or index. Usage: 'load_heightmap <file | number>'.");
476 return true;
479 if (argc != 2) return false;
481 const char *file = argv[1];
482 _console_file_list_heightmap.ValidateFileList();
483 const FiosItem *item = _console_file_list_heightmap.FindItem(file);
484 if (item != nullptr) {
485 if (GetAbstractFileType(item->type) == FT_HEIGHTMAP) {
486 _switch_mode = SM_START_HEIGHTMAP;
487 _file_to_saveload.Set(*item);
488 } else {
489 IConsolePrint(CC_ERROR, "'{}' is not a heightmap.", file);
491 } else {
492 IConsolePrint(CC_ERROR, "'{}' cannot be found.", file);
495 return true;
498 DEF_CONSOLE_CMD(ConRemove)
500 if (argc == 0) {
501 IConsolePrint(CC_HELP, "Remove a savegame by name or index. Usage: 'rm <file | number>'.");
502 return true;
505 if (argc != 2) return false;
507 const char *file = argv[1];
508 _console_file_list_savegame.ValidateFileList();
509 const FiosItem *item = _console_file_list_savegame.FindItem(file);
510 if (item != nullptr) {
511 if (unlink(item->name.c_str()) != 0) {
512 IConsolePrint(CC_ERROR, "Failed to delete '{}'.", item->name);
514 } else {
515 IConsolePrint(CC_ERROR, "'{}' could not be found.", file);
518 _console_file_list_savegame.InvalidateFileList();
519 return true;
523 /* List all the files in the current dir via console */
524 DEF_CONSOLE_CMD(ConListFiles)
526 if (argc == 0) {
527 IConsolePrint(CC_HELP, "List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'.");
528 return true;
531 _console_file_list_savegame.ValidateFileList(true);
532 for (uint i = 0; i < _console_file_list_savegame.size(); i++) {
533 IConsolePrint(CC_DEFAULT, "{}) {}", i, _console_file_list_savegame[i].title);
536 return true;
539 /* List all the scenarios */
540 DEF_CONSOLE_CMD(ConListScenarios)
542 if (argc == 0) {
543 IConsolePrint(CC_HELP, "List all loadable scenarios. Usage: 'list_scenarios'.");
544 return true;
547 _console_file_list_scenario.ValidateFileList(true);
548 for (uint i = 0; i < _console_file_list_scenario.size(); i++) {
549 IConsolePrint(CC_DEFAULT, "{}) {}", i, _console_file_list_scenario[i].title);
552 return true;
555 /* List all the heightmaps */
556 DEF_CONSOLE_CMD(ConListHeightmaps)
558 if (argc == 0) {
559 IConsolePrint(CC_HELP, "List all loadable heightmaps. Usage: 'list_heightmaps'.");
560 return true;
563 _console_file_list_heightmap.ValidateFileList(true);
564 for (uint i = 0; i < _console_file_list_heightmap.size(); i++) {
565 IConsolePrint(CC_DEFAULT, "{}) {}", i, _console_file_list_heightmap[i].title);
568 return true;
571 /* Change the dir via console */
572 DEF_CONSOLE_CMD(ConChangeDirectory)
574 if (argc == 0) {
575 IConsolePrint(CC_HELP, "Change the dir via console. Usage: 'cd <directory | number>'.");
576 return true;
579 if (argc != 2) return false;
581 const char *file = argv[1];
582 _console_file_list_savegame.ValidateFileList(true);
583 const FiosItem *item = _console_file_list_savegame.FindItem(file);
584 if (item != nullptr) {
585 switch (item->type) {
586 case FIOS_TYPE_DIR: case FIOS_TYPE_DRIVE: case FIOS_TYPE_PARENT:
587 FiosBrowseTo(item);
588 break;
589 default: IConsolePrint(CC_ERROR, "{}: Not a directory.", file);
591 } else {
592 IConsolePrint(CC_ERROR, "{}: No such file or directory.", file);
595 _console_file_list_savegame.InvalidateFileList();
596 return true;
599 DEF_CONSOLE_CMD(ConPrintWorkingDirectory)
601 if (argc == 0) {
602 IConsolePrint(CC_HELP, "Print out the current working directory. Usage: 'pwd'.");
603 return true;
606 /* XXX - Workaround for broken file handling */
607 _console_file_list_savegame.ValidateFileList(true);
608 _console_file_list_savegame.InvalidateFileList();
610 IConsolePrint(CC_DEFAULT, FiosGetCurrentPath());
611 return true;
614 DEF_CONSOLE_CMD(ConClearBuffer)
616 if (argc == 0) {
617 IConsolePrint(CC_HELP, "Clear the console buffer. Usage: 'clear'.");
618 return true;
621 IConsoleClearBuffer();
622 SetWindowDirty(WC_CONSOLE, 0);
623 return true;
627 /**********************************
628 * Network Core Console Commands
629 **********************************/
631 static bool ConKickOrBan(const char *argv, bool ban, const std::string &reason)
633 uint n;
635 if (strchr(argv, '.') == nullptr && strchr(argv, ':') == nullptr) { // banning with ID
636 ClientID client_id = (ClientID)atoi(argv);
638 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
639 * kicking frees closes and subsequently free the connection related instances, which we
640 * would be reading from and writing to after returning. So we would read or write data
641 * from freed memory up till the segfault triggers. */
642 if (client_id == CLIENT_ID_SERVER || client_id == _redirect_console_to_client) {
643 IConsolePrint(CC_ERROR, "You can not {} yourself!", ban ? "ban" : "kick");
644 return true;
647 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
648 if (ci == nullptr) {
649 IConsolePrint(CC_ERROR, "Invalid client ID.");
650 return true;
653 if (!ban) {
654 /* Kick only this client, not all clients with that IP */
655 NetworkServerKickClient(client_id, reason);
656 return true;
659 /* When banning, kick+ban all clients with that IP */
660 n = NetworkServerKickOrBanIP(client_id, ban, reason);
661 } else {
662 n = NetworkServerKickOrBanIP(argv, ban, reason);
665 if (n == 0) {
666 IConsolePrint(CC_DEFAULT, ban ? "Client not online, address added to banlist." : "Client not found.");
667 } else {
668 IConsolePrint(CC_DEFAULT, "{}ed {} client(s).", ban ? "Bann" : "Kick", n);
671 return true;
674 DEF_CONSOLE_CMD(ConKick)
676 if (argc == 0) {
677 IConsolePrint(CC_HELP, "Kick a client from a network game. Usage: 'kick <ip | client-id> [<kick-reason>]'.");
678 IConsolePrint(CC_HELP, "For client-id's, see the command 'clients'.");
679 return true;
682 if (argc != 2 && argc != 3) return false;
684 /* No reason supplied for kicking */
685 if (argc == 2) return ConKickOrBan(argv[1], false, {});
687 /* Reason for kicking supplied */
688 size_t kick_message_length = strlen(argv[2]);
689 if (kick_message_length >= 255) {
690 IConsolePrint(CC_ERROR, "Maximum kick message length is 254 characters. You entered {} characters.", kick_message_length);
691 return false;
692 } else {
693 return ConKickOrBan(argv[1], false, argv[2]);
697 DEF_CONSOLE_CMD(ConBan)
699 if (argc == 0) {
700 IConsolePrint(CC_HELP, "Ban a client from a network game. Usage: 'ban <ip | client-id> [<ban-reason>]'.");
701 IConsolePrint(CC_HELP, "For client-id's, see the command 'clients'.");
702 IConsolePrint(CC_HELP, "If the client is no longer online, you can still ban their IP.");
703 return true;
706 if (argc != 2 && argc != 3) return false;
708 /* No reason supplied for kicking */
709 if (argc == 2) return ConKickOrBan(argv[1], true, {});
711 /* Reason for kicking supplied */
712 size_t kick_message_length = strlen(argv[2]);
713 if (kick_message_length >= 255) {
714 IConsolePrint(CC_ERROR, "Maximum kick message length is 254 characters. You entered {} characters.", kick_message_length);
715 return false;
716 } else {
717 return ConKickOrBan(argv[1], true, argv[2]);
721 DEF_CONSOLE_CMD(ConUnBan)
723 if (argc == 0) {
724 IConsolePrint(CC_HELP, "Unban a client from a network game. Usage: 'unban <ip | banlist-index>'.");
725 IConsolePrint(CC_HELP, "For a list of banned IP's, see the command 'banlist'.");
726 return true;
729 if (argc != 2) return false;
731 /* Try by IP. */
732 uint index;
733 for (index = 0; index < _network_ban_list.size(); index++) {
734 if (_network_ban_list[index] == argv[1]) break;
737 /* Try by index. */
738 if (index >= _network_ban_list.size()) {
739 index = atoi(argv[1]) - 1U; // let it wrap
742 if (index < _network_ban_list.size()) {
743 IConsolePrint(CC_DEFAULT, "Unbanned {}.", _network_ban_list[index]);
744 _network_ban_list.erase(_network_ban_list.begin() + index);
745 } else {
746 IConsolePrint(CC_DEFAULT, "Invalid list index or IP not in ban-list.");
747 IConsolePrint(CC_DEFAULT, "For a list of banned IP's, see the command 'banlist'.");
750 return true;
753 DEF_CONSOLE_CMD(ConBanList)
755 if (argc == 0) {
756 IConsolePrint(CC_HELP, "List the IP's of banned clients: Usage 'banlist'.");
757 return true;
760 IConsolePrint(CC_DEFAULT, "Banlist:");
762 uint i = 1;
763 for (const auto &entry : _network_ban_list) {
764 IConsolePrint(CC_DEFAULT, " {}) {}", i, entry);
765 i++;
768 return true;
771 DEF_CONSOLE_CMD(ConPauseGame)
773 if (argc == 0) {
774 IConsolePrint(CC_HELP, "Pause a network game. Usage: 'pause'.");
775 return true;
778 if (_game_mode == GM_MENU) {
779 IConsolePrint(CC_ERROR, "This command is only available in-game and in the editor.");
780 return true;
783 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
784 Command<CMD_PAUSE>::Post(PM_PAUSED_NORMAL, true);
785 if (!_networking) IConsolePrint(CC_DEFAULT, "Game paused.");
786 } else {
787 IConsolePrint(CC_DEFAULT, "Game is already paused.");
790 return true;
793 DEF_CONSOLE_CMD(ConUnpauseGame)
795 if (argc == 0) {
796 IConsolePrint(CC_HELP, "Unpause a network game. Usage: 'unpause'.");
797 return true;
800 if (_game_mode == GM_MENU) {
801 IConsolePrint(CC_ERROR, "This command is only available in-game and in the editor.");
802 return true;
805 if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) {
806 Command<CMD_PAUSE>::Post(PM_PAUSED_NORMAL, false);
807 if (!_networking) IConsolePrint(CC_DEFAULT, "Game unpaused.");
808 } else if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED) {
809 IConsolePrint(CC_DEFAULT, "Game is in error state and cannot be unpaused via console.");
810 } else if (_pause_mode != PM_UNPAUSED) {
811 IConsolePrint(CC_DEFAULT, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
812 } else {
813 IConsolePrint(CC_DEFAULT, "Game is already unpaused.");
816 return true;
819 DEF_CONSOLE_CMD(ConRcon)
821 if (argc == 0) {
822 IConsolePrint(CC_HELP, "Remote control the server from another client. Usage: 'rcon <password> <command>'.");
823 IConsolePrint(CC_HELP, "Remember to enclose the command in quotes, otherwise only the first parameter is sent.");
824 return true;
827 if (argc < 3) return false;
829 if (_network_server) {
830 IConsoleCmdExec(argv[2]);
831 } else {
832 NetworkClientSendRcon(argv[1], argv[2]);
834 return true;
837 DEF_CONSOLE_CMD(ConStatus)
839 if (argc == 0) {
840 IConsolePrint(CC_HELP, "List the status of all clients connected to the server. Usage 'status'.");
841 return true;
844 NetworkServerShowStatusToConsole();
845 return true;
848 DEF_CONSOLE_CMD(ConServerInfo)
850 if (argc == 0) {
851 IConsolePrint(CC_HELP, "List current and maximum client/company limits. Usage 'server_info'.");
852 IConsolePrint(CC_HELP, "You can change these values by modifying settings 'network.max_clients' and 'network.max_companies'.");
853 return true;
856 IConsolePrint(CC_DEFAULT, "Invite code: {}", _network_server_invite_code);
857 IConsolePrint(CC_DEFAULT, "Current/maximum clients: {:3d}/{:3d}", _network_game_info.clients_on, _settings_client.network.max_clients);
858 IConsolePrint(CC_DEFAULT, "Current/maximum companies: {:3d}/{:3d}", Company::GetNumItems(), _settings_client.network.max_companies);
859 IConsolePrint(CC_DEFAULT, "Current spectators: {:3d}", NetworkSpectatorCount());
861 return true;
864 DEF_CONSOLE_CMD(ConClientNickChange)
866 if (argc != 3) {
867 IConsolePrint(CC_HELP, "Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'.");
868 IConsolePrint(CC_HELP, "For client-id's, see the command 'clients'.");
869 return true;
872 ClientID client_id = (ClientID)atoi(argv[1]);
874 if (client_id == CLIENT_ID_SERVER) {
875 IConsolePrint(CC_ERROR, "Please use the command 'name' to change your own name!");
876 return true;
879 if (NetworkClientInfo::GetByClientID(client_id) == nullptr) {
880 IConsolePrint(CC_ERROR, "Invalid client ID.");
881 return true;
884 std::string client_name(argv[2]);
885 StrTrimInPlace(client_name);
886 if (!NetworkIsValidClientName(client_name)) {
887 IConsolePrint(CC_ERROR, "Cannot give a client an empty name.");
888 return true;
891 if (!NetworkServerChangeClientName(client_id, client_name)) {
892 IConsolePrint(CC_ERROR, "Cannot give a client a duplicate name.");
895 return true;
898 DEF_CONSOLE_CMD(ConJoinCompany)
900 if (argc < 2) {
901 IConsolePrint(CC_HELP, "Request joining another company. Usage: 'join <company-id> [<password>]'.");
902 IConsolePrint(CC_HELP, "For valid company-id see company list, use 255 for spectator.");
903 return true;
906 CompanyID company_id = (CompanyID)(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1]));
908 /* Check we have a valid company id! */
909 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
910 IConsolePrint(CC_ERROR, "Company does not exist. Company-id must be between 1 and {}.", MAX_COMPANIES);
911 return true;
914 if (NetworkClientInfo::GetByClientID(_network_own_client_id)->client_playas == company_id) {
915 IConsolePrint(CC_ERROR, "You are already there!");
916 return true;
919 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
920 IConsolePrint(CC_ERROR, "Cannot join AI company.");
921 return true;
924 /* Check if the company requires a password */
925 if (NetworkCompanyIsPassworded(company_id) && argc < 3) {
926 IConsolePrint(CC_ERROR, "Company {} requires a password to join.", company_id + 1);
927 return true;
930 /* non-dedicated server may just do the move! */
931 if (_network_server) {
932 NetworkServerDoMove(CLIENT_ID_SERVER, company_id);
933 } else {
934 NetworkClientRequestMove(company_id, NetworkCompanyIsPassworded(company_id) ? argv[2] : "");
937 return true;
940 DEF_CONSOLE_CMD(ConMoveClient)
942 if (argc < 3) {
943 IConsolePrint(CC_HELP, "Move a client to another company. Usage: 'move <client-id> <company-id>'.");
944 IConsolePrint(CC_HELP, "For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators.");
945 return true;
948 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID((ClientID)atoi(argv[1]));
949 CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2]));
951 /* check the client exists */
952 if (ci == nullptr) {
953 IConsolePrint(CC_ERROR, "Invalid client-id, check the command 'clients' for valid client-id's.");
954 return true;
957 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
958 IConsolePrint(CC_ERROR, "Company does not exist. Company-id must be between 1 and {}.", MAX_COMPANIES);
959 return true;
962 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
963 IConsolePrint(CC_ERROR, "You cannot move clients to AI companies.");
964 return true;
967 if (ci->client_id == CLIENT_ID_SERVER && _network_dedicated) {
968 IConsolePrint(CC_ERROR, "You cannot move the server!");
969 return true;
972 if (ci->client_playas == company_id) {
973 IConsolePrint(CC_ERROR, "You cannot move someone to where they already are!");
974 return true;
977 /* we are the server, so force the update */
978 NetworkServerDoMove(ci->client_id, company_id);
980 return true;
983 DEF_CONSOLE_CMD(ConResetCompany)
985 if (argc == 0) {
986 IConsolePrint(CC_HELP, "Remove an idle company from the game. Usage: 'reset_company <company-id>'.");
987 IConsolePrint(CC_HELP, "For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
988 return true;
991 if (argc != 2) return false;
993 CompanyID index = (CompanyID)(atoi(argv[1]) - 1);
995 /* Check valid range */
996 if (!Company::IsValidID(index)) {
997 IConsolePrint(CC_ERROR, "Company does not exist. Company-id must be between 1 and {}.", MAX_COMPANIES);
998 return true;
1001 if (!Company::IsHumanID(index)) {
1002 IConsolePrint(CC_ERROR, "Company is owned by an AI.");
1003 return true;
1006 if (NetworkCompanyHasClients(index)) {
1007 IConsolePrint(CC_ERROR, "Cannot remove company: a client is connected to that company.");
1008 return false;
1010 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
1011 assert(ci != nullptr);
1012 if (ci->client_playas == index) {
1013 IConsolePrint(CC_ERROR, "Cannot remove company: the server is connected to that company.");
1014 return true;
1017 /* It is safe to remove this company */
1018 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, index, CRR_MANUAL, INVALID_CLIENT_ID);
1019 IConsolePrint(CC_DEFAULT, "Company deleted.");
1021 return true;
1024 DEF_CONSOLE_CMD(ConNetworkClients)
1026 if (argc == 0) {
1027 IConsolePrint(CC_HELP, "Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'.");
1028 return true;
1031 NetworkPrintClients();
1033 return true;
1036 DEF_CONSOLE_CMD(ConNetworkReconnect)
1038 if (argc == 0) {
1039 IConsolePrint(CC_HELP, "Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'.");
1040 IConsolePrint(CC_HELP, "Company 255 is spectator (default, if not specified), 0 means creating new company.");
1041 IConsolePrint(CC_HELP, "All others are a certain company with Company 1 being #1.");
1042 return true;
1045 CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR;
1046 switch (playas) {
1047 case 0: playas = COMPANY_NEW_COMPANY; break;
1048 case COMPANY_SPECTATOR: /* nothing to do */ break;
1049 default:
1050 /* From a user pov 0 is a new company, internally it's different and all
1051 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
1052 if (playas < COMPANY_FIRST + 1 || playas > MAX_COMPANIES + 1) return false;
1053 break;
1056 if (_settings_client.network.last_joined.empty()) {
1057 IConsolePrint(CC_DEFAULT, "No server for reconnecting.");
1058 return true;
1061 /* Don't resolve the address first, just print it directly as it comes from the config file. */
1062 IConsolePrint(CC_DEFAULT, "Reconnecting to {} ...", _settings_client.network.last_joined);
1064 return NetworkClientConnectGame(_settings_client.network.last_joined, playas);
1067 DEF_CONSOLE_CMD(ConNetworkConnect)
1069 if (argc == 0) {
1070 IConsolePrint(CC_HELP, "Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'.");
1071 IConsolePrint(CC_HELP, "IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'.");
1072 IConsolePrint(CC_HELP, "Company #255 is spectator all others are a certain company with Company 1 being #1.");
1073 return true;
1076 if (argc < 2) return false;
1078 return NetworkClientConnectGame(argv[1], COMPANY_NEW_COMPANY);
1081 /*********************************
1082 * script file console commands
1083 *********************************/
1085 DEF_CONSOLE_CMD(ConExec)
1087 if (argc == 0) {
1088 IConsolePrint(CC_HELP, "Execute a local script file. Usage: 'exec <script> <?>'.");
1089 return true;
1092 if (argc < 2) return false;
1094 FILE *script_file = FioFOpenFile(argv[1], "r", BASE_DIR);
1096 if (script_file == nullptr) {
1097 if (argc == 2 || atoi(argv[2]) != 0) IConsolePrint(CC_ERROR, "Script file '{}' not found.", argv[1]);
1098 return true;
1101 if (_script_current_depth == 11) {
1102 FioFCloseFile(script_file);
1103 IConsolePrint(CC_ERROR, "Maximum 'exec' depth reached; script A is calling script B is calling script C ... more than 10 times.");
1104 return true;
1107 _script_current_depth++;
1108 uint script_depth = _script_current_depth;
1110 char cmdline[ICON_CMDLN_SIZE];
1111 while (fgets(cmdline, sizeof(cmdline), script_file) != nullptr) {
1112 /* Remove newline characters from the executing script */
1113 for (char *cmdptr = cmdline; *cmdptr != '\0'; cmdptr++) {
1114 if (*cmdptr == '\n' || *cmdptr == '\r') {
1115 *cmdptr = '\0';
1116 break;
1119 IConsoleCmdExec(cmdline);
1120 /* Ensure that we are still on the same depth or that we returned via 'return'. */
1121 assert(_script_current_depth == script_depth || _script_current_depth == script_depth - 1);
1123 /* The 'return' command was executed. */
1124 if (_script_current_depth == script_depth - 1) break;
1127 if (ferror(script_file)) {
1128 IConsolePrint(CC_ERROR, "Encountered error while trying to read from script file '{}'.", argv[1]);
1131 if (_script_current_depth == script_depth) _script_current_depth--;
1132 FioFCloseFile(script_file);
1133 return true;
1136 DEF_CONSOLE_CMD(ConReturn)
1138 if (argc == 0) {
1139 IConsolePrint(CC_HELP, "Stop executing a running script. Usage: 'return'.");
1140 return true;
1143 _script_current_depth--;
1144 return true;
1147 /*****************************
1148 * default console commands
1149 ******************************/
1150 extern bool CloseConsoleLogIfActive();
1151 extern const std::vector<GRFFile *> &GetAllGRFFiles();
1152 extern void ConPrintFramerate(); // framerate_gui.cpp
1153 extern void ShowFramerateWindow();
1155 DEF_CONSOLE_CMD(ConScript)
1157 extern FILE *_iconsole_output_file;
1159 if (argc == 0) {
1160 IConsolePrint(CC_HELP, "Start or stop logging console output to a file. Usage: 'script <filename>'.");
1161 IConsolePrint(CC_HELP, "If filename is omitted, a running log is stopped if it is active.");
1162 return true;
1165 if (!CloseConsoleLogIfActive()) {
1166 if (argc < 2) return false;
1168 _iconsole_output_file = fopen(argv[1], "ab");
1169 if (_iconsole_output_file == nullptr) {
1170 IConsolePrint(CC_ERROR, "Could not open console log file '{}'.", argv[1]);
1171 } else {
1172 IConsolePrint(CC_INFO, "Console log output started to '{}'.", argv[1]);
1176 return true;
1180 DEF_CONSOLE_CMD(ConEcho)
1182 if (argc == 0) {
1183 IConsolePrint(CC_HELP, "Print back the first argument to the console. Usage: 'echo <arg>'.");
1184 return true;
1187 if (argc < 2) return false;
1188 IConsolePrint(CC_DEFAULT, argv[1]);
1189 return true;
1192 DEF_CONSOLE_CMD(ConEchoC)
1194 if (argc == 0) {
1195 IConsolePrint(CC_HELP, "Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'.");
1196 return true;
1199 if (argc < 3) return false;
1200 IConsolePrint((TextColour)Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1), argv[2]);
1201 return true;
1204 DEF_CONSOLE_CMD(ConNewGame)
1206 if (argc == 0) {
1207 IConsolePrint(CC_HELP, "Start a new game. Usage: 'newgame [seed]'.");
1208 IConsolePrint(CC_HELP, "The server can force a new game using 'newgame'; any client joined will rejoin after the server is done generating the new game.");
1209 return true;
1212 StartNewGameWithoutGUI((argc == 2) ? std::strtoul(argv[1], nullptr, 10) : GENERATE_NEW_SEED);
1213 return true;
1216 DEF_CONSOLE_CMD(ConRestart)
1218 if (argc == 0 || argc > 2) {
1219 IConsolePrint(CC_HELP, "Restart game. Usage: 'restart [current|newgame]'.");
1220 IConsolePrint(CC_HELP, "Restarts a game, using either the current or newgame (default) settings.");
1221 IConsolePrint(CC_HELP, " * if you started from a new game, and your current/newgame settings haven't changed, the game will be identical to when you started it.");
1222 IConsolePrint(CC_HELP, " * if you started from a savegame / scenario / heightmap, the game might be different, because the current/newgame settings might differ.");
1223 return true;
1226 if (argc == 1 || std::string_view(argv[1]) == "newgame") {
1227 StartNewGameWithoutGUI(_settings_game.game_creation.generation_seed);
1228 } else {
1229 _settings_game.game_creation.map_x = Map::LogX();
1230 _settings_game.game_creation.map_y = Map::LogY();
1231 _switch_mode = SM_RESTARTGAME;
1234 return true;
1237 DEF_CONSOLE_CMD(ConReload)
1239 if (argc == 0) {
1240 IConsolePrint(CC_HELP, "Reload game. Usage: 'reload'.");
1241 IConsolePrint(CC_HELP, "Reloads a game if loaded via savegame / scenario / heightmap.");
1242 return true;
1245 if (_file_to_saveload.abstract_ftype == FT_NONE || _file_to_saveload.abstract_ftype == FT_INVALID) {
1246 IConsolePrint(CC_ERROR, "No game loaded to reload.");
1247 return true;
1250 /* Use a switch-mode to prevent copying over newgame settings to active settings. */
1251 _settings_game.game_creation.map_x = Map::LogX();
1252 _settings_game.game_creation.map_y = Map::LogY();
1253 _switch_mode = SM_RELOADGAME;
1254 return true;
1258 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1259 * @param full_string The multi-line string to print.
1261 static void PrintLineByLine(const std::string &full_string)
1263 std::istringstream in(full_string);
1264 std::string line;
1265 while (std::getline(in, line)) {
1266 IConsolePrint(CC_DEFAULT, line);
1270 template <typename F, typename ... Args>
1271 bool PrintList(F list_function, Args... args)
1273 std::string output_str;
1274 auto inserter = std::back_inserter(output_str);
1275 list_function(inserter, args...);
1276 PrintLineByLine(output_str);
1278 return true;
1281 DEF_CONSOLE_CMD(ConListAILibs)
1283 if (argc == 0) {
1284 IConsolePrint(CC_HELP, "List installed AI libraries. Usage: 'list_ai_libs'.");
1285 return true;
1288 return PrintList(AI::GetConsoleLibraryList);
1291 DEF_CONSOLE_CMD(ConListAI)
1293 if (argc == 0) {
1294 IConsolePrint(CC_HELP, "List installed AIs. Usage: 'list_ai'.");
1295 return true;
1298 return PrintList(AI::GetConsoleList, false);
1301 DEF_CONSOLE_CMD(ConListGameLibs)
1303 if (argc == 0) {
1304 IConsolePrint(CC_HELP, "List installed Game Script libraries. Usage: 'list_game_libs'.");
1305 return true;
1308 return PrintList(Game::GetConsoleLibraryList);
1311 DEF_CONSOLE_CMD(ConListGame)
1313 if (argc == 0) {
1314 IConsolePrint(CC_HELP, "List installed Game Scripts. Usage: 'list_game'.");
1315 return true;
1318 return PrintList(Game::GetConsoleList, false);
1321 DEF_CONSOLE_CMD(ConStartAI)
1323 if (argc == 0 || argc > 3) {
1324 IConsolePrint(CC_HELP, "Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'.");
1325 IConsolePrint(CC_HELP, "Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1326 IConsolePrint(CC_HELP, "If <settings> is given, it is parsed and the AI settings are set to that.");
1327 return true;
1330 if (_game_mode != GM_NORMAL) {
1331 IConsolePrint(CC_ERROR, "AIs can only be managed in a game.");
1332 return true;
1335 if (Company::GetNumItems() == CompanyPool::MAX_SIZE) {
1336 IConsolePrint(CC_ERROR, "Can't start a new AI (no more free slots).");
1337 return true;
1339 if (_networking && !_network_server) {
1340 IConsolePrint(CC_ERROR, "Only the server can start a new AI.");
1341 return true;
1343 if (_networking && !_settings_game.ai.ai_in_multiplayer) {
1344 IConsolePrint(CC_ERROR, "AIs are not allowed in multiplayer by configuration.");
1345 IConsolePrint(CC_ERROR, "Switch AI -> AI in multiplayer to True.");
1346 return true;
1348 if (!AI::CanStartNew()) {
1349 IConsolePrint(CC_ERROR, "Can't start a new AI.");
1350 return true;
1353 int n = 0;
1354 /* Find the next free slot */
1355 for (const Company *c : Company::Iterate()) {
1356 if (c->index != n) break;
1357 n++;
1360 AIConfig *config = AIConfig::GetConfig((CompanyID)n);
1361 if (argc >= 2) {
1362 config->Change(argv[1], -1, false);
1364 /* If the name is not found, and there is a dot in the name,
1365 * try again with the assumption everything right of the dot is
1366 * the version the user wants to load. */
1367 if (!config->HasScript()) {
1368 const char *e = strrchr(argv[1], '.');
1369 if (e != nullptr) {
1370 size_t name_length = e - argv[1];
1371 e++;
1373 int version = atoi(e);
1374 config->Change(std::string(argv[1], name_length), version, true);
1378 if (!config->HasScript()) {
1379 IConsolePrint(CC_ERROR, "Failed to load the specified AI.");
1380 return true;
1382 if (argc == 3) {
1383 config->StringToSettings(argv[2]);
1387 /* Start a new AI company */
1388 Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, INVALID_COMPANY, CRR_NONE, INVALID_CLIENT_ID);
1390 return true;
1393 DEF_CONSOLE_CMD(ConReloadAI)
1395 if (argc != 2) {
1396 IConsolePrint(CC_HELP, "Reload an AI. Usage: 'reload_ai <company-id>'.");
1397 IConsolePrint(CC_HELP, "Reload the AI with the given company id. For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
1398 return true;
1401 if (_game_mode != GM_NORMAL) {
1402 IConsolePrint(CC_ERROR, "AIs can only be managed in a game.");
1403 return true;
1406 if (_networking && !_network_server) {
1407 IConsolePrint(CC_ERROR, "Only the server can reload an AI.");
1408 return true;
1411 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1412 if (!Company::IsValidID(company_id)) {
1413 IConsolePrint(CC_ERROR, "Unknown company. Company range is between 1 and {}.", MAX_COMPANIES);
1414 return true;
1417 /* In singleplayer mode the player can be in an AI company, after cheating or loading network save with an AI in first slot. */
1418 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1419 IConsolePrint(CC_ERROR, "Company is not controlled by an AI.");
1420 return true;
1423 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1424 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, company_id, CRR_MANUAL, INVALID_CLIENT_ID);
1425 Command<CMD_COMPANY_CTRL>::Post(CCA_NEW_AI, company_id, CRR_NONE, INVALID_CLIENT_ID);
1426 IConsolePrint(CC_DEFAULT, "AI reloaded.");
1428 return true;
1431 DEF_CONSOLE_CMD(ConStopAI)
1433 if (argc != 2) {
1434 IConsolePrint(CC_HELP, "Stop an AI. Usage: 'stop_ai <company-id>'.");
1435 IConsolePrint(CC_HELP, "Stop the AI with the given company id. For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
1436 return true;
1439 if (_game_mode != GM_NORMAL) {
1440 IConsolePrint(CC_ERROR, "AIs can only be managed in a game.");
1441 return true;
1444 if (_networking && !_network_server) {
1445 IConsolePrint(CC_ERROR, "Only the server can stop an AI.");
1446 return true;
1449 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1450 if (!Company::IsValidID(company_id)) {
1451 IConsolePrint(CC_ERROR, "Unknown company. Company range is between 1 and {}.", MAX_COMPANIES);
1452 return true;
1455 /* In singleplayer mode the player can be in an AI company, after cheating or loading network save with an AI in first slot. */
1456 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1457 IConsolePrint(CC_ERROR, "Company is not controlled by an AI.");
1458 return true;
1461 /* Now kill the company of the AI. */
1462 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, company_id, CRR_MANUAL, INVALID_CLIENT_ID);
1463 IConsolePrint(CC_DEFAULT, "AI stopped, company deleted.");
1465 return true;
1468 DEF_CONSOLE_CMD(ConRescanAI)
1470 if (argc == 0) {
1471 IConsolePrint(CC_HELP, "Rescan the AI dir for scripts. Usage: 'rescan_ai'.");
1472 return true;
1475 if (_networking && !_network_server) {
1476 IConsolePrint(CC_ERROR, "Only the server can rescan the AI dir for scripts.");
1477 return true;
1480 AI::Rescan();
1482 return true;
1485 DEF_CONSOLE_CMD(ConRescanGame)
1487 if (argc == 0) {
1488 IConsolePrint(CC_HELP, "Rescan the Game Script dir for scripts. Usage: 'rescan_game'.");
1489 return true;
1492 if (_networking && !_network_server) {
1493 IConsolePrint(CC_ERROR, "Only the server can rescan the Game Script dir for scripts.");
1494 return true;
1497 Game::Rescan();
1499 return true;
1502 DEF_CONSOLE_CMD(ConRescanNewGRF)
1504 if (argc == 0) {
1505 IConsolePrint(CC_HELP, "Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'.");
1506 return true;
1509 if (!RequestNewGRFScan()) {
1510 IConsolePrint(CC_ERROR, "NewGRF scanning is already running. Please wait until completed to run again.");
1513 return true;
1516 DEF_CONSOLE_CMD(ConGetSeed)
1518 if (argc == 0) {
1519 IConsolePrint(CC_HELP, "Returns the seed used to create this game. Usage: 'getseed'.");
1520 IConsolePrint(CC_HELP, "The seed can be used to reproduce the exact same map as the game started with.");
1521 return true;
1524 IConsolePrint(CC_DEFAULT, "Generation Seed: {}", _settings_game.game_creation.generation_seed);
1525 return true;
1528 DEF_CONSOLE_CMD(ConGetDate)
1530 if (argc == 0) {
1531 IConsolePrint(CC_HELP, "Returns the current date (year-month-day) of the game. Usage: 'getdate'.");
1532 return true;
1535 TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(TimerGameCalendar::date);
1536 IConsolePrint(CC_DEFAULT, "Date: {:04d}-{:02d}-{:02d}", ymd.year, ymd.month + 1, ymd.day);
1537 return true;
1540 DEF_CONSOLE_CMD(ConGetSysDate)
1542 if (argc == 0) {
1543 IConsolePrint(CC_HELP, "Returns the current date (year-month-day) of your system. Usage: 'getsysdate'.");
1544 return true;
1547 IConsolePrint(CC_DEFAULT, "System Date: {:%Y-%m-%d %H:%M:%S}", fmt::localtime(time(nullptr)));
1548 return true;
1552 DEF_CONSOLE_CMD(ConAlias)
1554 IConsoleAlias *alias;
1556 if (argc == 0) {
1557 IConsolePrint(CC_HELP, "Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'.");
1558 return true;
1561 if (argc < 3) return false;
1563 alias = IConsole::AliasGet(argv[1]);
1564 if (alias == nullptr) {
1565 IConsole::AliasRegister(argv[1], argv[2]);
1566 } else {
1567 alias->cmdline = argv[2];
1569 return true;
1572 DEF_CONSOLE_CMD(ConScreenShot)
1574 if (argc == 0) {
1575 IConsolePrint(CC_HELP, "Create a screenshot of the game. Usage: 'screenshot [viewport | normal | big | giant | heightmap | minimap] [no_con] [size <width> <height>] [<filename>]'.");
1576 IConsolePrint(CC_HELP, " 'viewport' (default) makes a screenshot of the current viewport (including menus, windows).");
1577 IConsolePrint(CC_HELP, " 'normal' makes a screenshot of the visible area.");
1578 IConsolePrint(CC_HELP, " 'big' makes a zoomed-in screenshot of the visible area.");
1579 IConsolePrint(CC_HELP, " 'giant' makes a screenshot of the whole map.");
1580 IConsolePrint(CC_HELP, " 'heightmap' makes a heightmap screenshot of the map that can be loaded in as heightmap.");
1581 IConsolePrint(CC_HELP, " 'minimap' makes a top-viewed minimap screenshot of the whole world which represents one tile by one pixel.");
1582 IConsolePrint(CC_HELP, " 'no_con' hides the console to create the screenshot (only useful in combination with 'viewport').");
1583 IConsolePrint(CC_HELP, " 'size' sets the width and height of the viewport to make a screenshot of (only useful in combination with 'normal' or 'big').");
1584 IConsolePrint(CC_HELP, " A filename ending in # will prevent overwriting existing files and will number files counting upwards.");
1585 return true;
1588 if (argc > 7) return false;
1590 ScreenshotType type = SC_VIEWPORT;
1591 uint32_t width = 0;
1592 uint32_t height = 0;
1593 std::string name{};
1594 uint32_t arg_index = 1;
1596 if (argc > arg_index) {
1597 if (strcmp(argv[arg_index], "viewport") == 0) {
1598 type = SC_VIEWPORT;
1599 arg_index += 1;
1600 } else if (strcmp(argv[arg_index], "normal") == 0) {
1601 type = SC_DEFAULTZOOM;
1602 arg_index += 1;
1603 } else if (strcmp(argv[arg_index], "big") == 0) {
1604 type = SC_ZOOMEDIN;
1605 arg_index += 1;
1606 } else if (strcmp(argv[arg_index], "giant") == 0) {
1607 type = SC_WORLD;
1608 arg_index += 1;
1609 } else if (strcmp(argv[arg_index], "heightmap") == 0) {
1610 type = SC_HEIGHTMAP;
1611 arg_index += 1;
1612 } else if (strcmp(argv[arg_index], "minimap") == 0) {
1613 type = SC_MINIMAP;
1614 arg_index += 1;
1618 if (argc > arg_index && strcmp(argv[arg_index], "no_con") == 0) {
1619 if (type != SC_VIEWPORT) {
1620 IConsolePrint(CC_ERROR, "'no_con' can only be used in combination with 'viewport'.");
1621 return true;
1623 IConsoleClose();
1624 arg_index += 1;
1627 if (argc > arg_index + 2 && strcmp(argv[arg_index], "size") == 0) {
1628 /* size <width> <height> */
1629 if (type != SC_DEFAULTZOOM && type != SC_ZOOMEDIN) {
1630 IConsolePrint(CC_ERROR, "'size' can only be used in combination with 'normal' or 'big'.");
1631 return true;
1633 GetArgumentInteger(&width, argv[arg_index + 1]);
1634 GetArgumentInteger(&height, argv[arg_index + 2]);
1635 arg_index += 3;
1638 if (argc > arg_index) {
1639 /* Last parameter that was not one of the keywords must be the filename. */
1640 name = argv[arg_index];
1641 arg_index += 1;
1644 if (argc > arg_index) {
1645 /* We have parameters we did not process; means we misunderstood any of the above. */
1646 return false;
1649 MakeScreenshot(type, name, width, height);
1650 return true;
1653 DEF_CONSOLE_CMD(ConInfoCmd)
1655 if (argc == 0) {
1656 IConsolePrint(CC_HELP, "Print out debugging information about a command. Usage: 'info_cmd <cmd>'.");
1657 return true;
1660 if (argc < 2) return false;
1662 const IConsoleCmd *cmd = IConsole::CmdGet(argv[1]);
1663 if (cmd == nullptr) {
1664 IConsolePrint(CC_ERROR, "The given command was not found.");
1665 return true;
1668 IConsolePrint(CC_DEFAULT, "Command name: '{}'", cmd->name);
1670 if (cmd->hook != nullptr) IConsolePrint(CC_DEFAULT, "Command is hooked.");
1672 return true;
1675 DEF_CONSOLE_CMD(ConDebugLevel)
1677 if (argc == 0) {
1678 IConsolePrint(CC_HELP, "Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'.");
1679 IConsolePrint(CC_HELP, "Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'\"s.");
1680 return true;
1683 if (argc > 2) return false;
1685 if (argc == 1) {
1686 IConsolePrint(CC_DEFAULT, "Current debug-level: '{}'", GetDebugString());
1687 } else {
1688 SetDebugString(argv[1], [](const std::string &err) { IConsolePrint(CC_ERROR, err); });
1691 return true;
1694 DEF_CONSOLE_CMD(ConExit)
1696 if (argc == 0) {
1697 IConsolePrint(CC_HELP, "Exit the game. Usage: 'exit'.");
1698 return true;
1701 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
1703 _exit_game = true;
1704 return true;
1707 DEF_CONSOLE_CMD(ConPart)
1709 if (argc == 0) {
1710 IConsolePrint(CC_HELP, "Leave the currently joined/running game (only ingame). Usage: 'part'.");
1711 return true;
1714 if (_game_mode != GM_NORMAL) return false;
1716 if (_network_dedicated) {
1717 IConsolePrint(CC_ERROR, "A dedicated server can not leave the game.");
1718 return false;
1721 _switch_mode = SM_MENU;
1722 return true;
1725 DEF_CONSOLE_CMD(ConHelp)
1727 if (argc == 2) {
1728 const IConsoleCmd *cmd;
1729 const IConsoleAlias *alias;
1731 cmd = IConsole::CmdGet(argv[1]);
1732 if (cmd != nullptr) {
1733 cmd->proc(0, nullptr);
1734 return true;
1737 alias = IConsole::AliasGet(argv[1]);
1738 if (alias != nullptr) {
1739 cmd = IConsole::CmdGet(alias->cmdline);
1740 if (cmd != nullptr) {
1741 cmd->proc(0, nullptr);
1742 return true;
1744 IConsolePrint(CC_ERROR, "Alias is of special type, please see its execution-line: '{}'.", alias->cmdline);
1745 return true;
1748 IConsolePrint(CC_ERROR, "Command not found.");
1749 return true;
1752 IConsolePrint(TC_LIGHT_BLUE, " ---- OpenTTD Console Help ---- ");
1753 IConsolePrint(CC_DEFAULT, " - commands: the command to list all commands is 'list_cmds'.");
1754 IConsolePrint(CC_DEFAULT, " call commands with '<command> <arg2> <arg3>...'");
1755 IConsolePrint(CC_DEFAULT, " - to assign strings, or use them as arguments, enclose it within quotes.");
1756 IConsolePrint(CC_DEFAULT, " like this: '<command> \"string argument with spaces\"'.");
1757 IConsolePrint(CC_DEFAULT, " - use 'help <command>' to get specific information.");
1758 IConsolePrint(CC_DEFAULT, " - scroll console output with shift + (up | down | pageup | pagedown).");
1759 IConsolePrint(CC_DEFAULT, " - scroll console input history with the up or down arrows.");
1760 IConsolePrint(CC_DEFAULT, "");
1761 return true;
1764 DEF_CONSOLE_CMD(ConListCommands)
1766 if (argc == 0) {
1767 IConsolePrint(CC_HELP, "List all registered commands. Usage: 'list_cmds [<pre-filter>]'.");
1768 return true;
1771 for (auto &it : IConsole::Commands()) {
1772 const IConsoleCmd *cmd = &it.second;
1773 if (argv[1] == nullptr || cmd->name.find(argv[1]) != std::string::npos) {
1774 if (cmd->hook == nullptr || cmd->hook(false) != CHR_HIDE) IConsolePrint(CC_DEFAULT, cmd->name);
1778 return true;
1781 DEF_CONSOLE_CMD(ConListAliases)
1783 if (argc == 0) {
1784 IConsolePrint(CC_HELP, "List all registered aliases. Usage: 'list_aliases [<pre-filter>]'.");
1785 return true;
1788 for (auto &it : IConsole::Aliases()) {
1789 const IConsoleAlias *alias = &it.second;
1790 if (argv[1] == nullptr || alias->name.find(argv[1]) != std::string::npos) {
1791 IConsolePrint(CC_DEFAULT, "{} => {}", alias->name, alias->cmdline);
1795 return true;
1798 DEF_CONSOLE_CMD(ConCompanies)
1800 if (argc == 0) {
1801 IConsolePrint(CC_HELP, "List the details of all companies in the game. Usage 'companies'.");
1802 return true;
1805 for (const Company *c : Company::Iterate()) {
1806 /* Grab the company name */
1807 SetDParam(0, c->index);
1808 std::string company_name = GetString(STR_COMPANY_NAME);
1810 const char *password_state = "";
1811 if (c->is_ai) {
1812 password_state = "AI";
1813 } else if (_network_server) {
1814 password_state = _network_company_states[c->index].password.empty() ? "unprotected" : "protected";
1817 std::string colour = GetString(STR_COLOUR_DARK_BLUE + _company_colours[c->index]);
1818 IConsolePrint(CC_INFO, "#:{}({}) Company Name: '{}' Year Founded: {} Money: {} Loan: {} Value: {} (T:{}, R:{}, P:{}, S:{}) {}",
1819 c->index + 1, colour, company_name,
1820 c->inaugurated_year, (int64_t)c->money, (int64_t)c->current_loan, (int64_t)CalculateCompanyValue(c),
1821 c->group_all[VEH_TRAIN].num_vehicle,
1822 c->group_all[VEH_ROAD].num_vehicle,
1823 c->group_all[VEH_AIRCRAFT].num_vehicle,
1824 c->group_all[VEH_SHIP].num_vehicle,
1825 password_state);
1828 return true;
1831 DEF_CONSOLE_CMD(ConSay)
1833 if (argc == 0) {
1834 IConsolePrint(CC_HELP, "Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'.");
1835 return true;
1838 if (argc != 2) return false;
1840 if (!_network_server) {
1841 NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
1842 } else {
1843 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1844 NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin);
1847 return true;
1850 DEF_CONSOLE_CMD(ConSayCompany)
1852 if (argc == 0) {
1853 IConsolePrint(CC_HELP, "Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'.");
1854 IConsolePrint(CC_HELP, "CompanyNo is the company that plays as company <companyno>, 1 through max_companies.");
1855 return true;
1858 if (argc != 3) return false;
1860 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1861 if (!Company::IsValidID(company_id)) {
1862 IConsolePrint(CC_DEFAULT, "Unknown company. Company range is between 1 and {}.", MAX_COMPANIES);
1863 return true;
1866 if (!_network_server) {
1867 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]);
1868 } else {
1869 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1870 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2], CLIENT_ID_SERVER, from_admin);
1873 return true;
1876 DEF_CONSOLE_CMD(ConSayClient)
1878 if (argc == 0) {
1879 IConsolePrint(CC_HELP, "Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'.");
1880 IConsolePrint(CC_HELP, "For client-id's, see the command 'clients'.");
1881 return true;
1884 if (argc != 3) return false;
1886 if (!_network_server) {
1887 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
1888 } else {
1889 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1890 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin);
1893 return true;
1896 DEF_CONSOLE_CMD(ConCompanyPassword)
1898 if (argc == 0) {
1899 if (_network_dedicated) {
1900 IConsolePrint(CC_HELP, "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\".");
1901 } else if (_network_server) {
1902 IConsolePrint(CC_HELP, "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'.");
1903 } else {
1904 IConsolePrint(CC_HELP, "Change the password of your company. Usage: 'company_pw \"<password>\"'.");
1907 IConsolePrint(CC_HELP, "Use \"*\" to disable the password.");
1908 return true;
1911 CompanyID company_id;
1912 std::string password;
1913 const char *errormsg;
1915 if (argc == 2) {
1916 company_id = _local_company;
1917 password = argv[1];
1918 errormsg = "You have to own a company to make use of this command.";
1919 } else if (argc == 3 && _network_server) {
1920 company_id = (CompanyID)(atoi(argv[1]) - 1);
1921 password = argv[2];
1922 errormsg = "You have to specify the ID of a valid human controlled company.";
1923 } else {
1924 return false;
1927 if (!Company::IsValidHumanID(company_id)) {
1928 IConsolePrint(CC_ERROR, errormsg);
1929 return false;
1932 password = NetworkChangeCompanyPassword(company_id, password);
1934 if (password.empty()) {
1935 IConsolePrint(CC_INFO, "Company password cleared.");
1936 } else {
1937 IConsolePrint(CC_INFO, "Company password changed to '{}'.", password);
1940 return true;
1943 /* Content downloading only is available with ZLIB */
1944 #if defined(WITH_ZLIB)
1945 #include "network/network_content.h"
1947 /** Resolve a string to a content type. */
1948 static ContentType StringToContentType(const char *str)
1950 static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1951 for (uint i = 1 /* there is no type 0 */; i < lengthof(inv_lookup); i++) {
1952 if (StrEqualsIgnoreCase(str, inv_lookup[i])) return (ContentType)i;
1954 return CONTENT_TYPE_END;
1957 /** Asynchronous callback */
1958 struct ConsoleContentCallback : public ContentCallback {
1959 void OnConnect(bool success) override
1961 IConsolePrint(CC_DEFAULT, "Content server connection {}.", success ? "established" : "failed");
1964 void OnDisconnect() override
1966 IConsolePrint(CC_DEFAULT, "Content server connection closed.");
1969 void OnDownloadComplete(ContentID cid) override
1971 IConsolePrint(CC_DEFAULT, "Completed download of {}.", cid);
1976 * Outputs content state information to console
1977 * @param ci the content info
1979 static void OutputContentState(const ContentInfo *const ci)
1981 static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1982 static_assert(lengthof(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN);
1983 static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1984 static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR };
1986 IConsolePrint(state_to_colour[ci->state], "{}, {}, {}, {}, {:08X}, {}", ci->id, types[ci->type - 1], states[ci->state], ci->name, ci->unique_id, FormatArrayAsHex(ci->md5sum));
1989 DEF_CONSOLE_CMD(ConContent)
1991 static ContentCallback *cb = nullptr;
1992 if (cb == nullptr) {
1993 cb = new ConsoleContentCallback();
1994 _network_content_client.AddCallback(cb);
1997 if (argc <= 1) {
1998 IConsolePrint(CC_HELP, "Query, select and download content. Usage: 'content update|upgrade|select [id]|unselect [all|id]|state [filter]|download'.");
1999 IConsolePrint(CC_HELP, " update: get a new list of downloadable content; must be run first.");
2000 IConsolePrint(CC_HELP, " upgrade: select all items that are upgrades.");
2001 IConsolePrint(CC_HELP, " select: select a specific item given by its id. If no parameter is given, all selected content will be listed.");
2002 IConsolePrint(CC_HELP, " unselect: unselect a specific item given by its id or 'all' to unselect all.");
2003 IConsolePrint(CC_HELP, " state: show the download/select state of all downloadable content. Optionally give a filter string.");
2004 IConsolePrint(CC_HELP, " download: download all content you've selected.");
2005 return true;
2008 if (StrEqualsIgnoreCase(argv[1], "update")) {
2009 _network_content_client.RequestContentList((argc > 2) ? StringToContentType(argv[2]) : CONTENT_TYPE_END);
2010 return true;
2013 if (StrEqualsIgnoreCase(argv[1], "upgrade")) {
2014 _network_content_client.SelectUpgrade();
2015 return true;
2018 if (StrEqualsIgnoreCase(argv[1], "select")) {
2019 if (argc <= 2) {
2020 /* List selected content */
2021 IConsolePrint(CC_WHITE, "id, type, state, name");
2022 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
2023 if ((*iter)->state != ContentInfo::SELECTED && (*iter)->state != ContentInfo::AUTOSELECTED) continue;
2024 OutputContentState(*iter);
2026 } else if (StrEqualsIgnoreCase(argv[2], "all")) {
2027 /* The intention of this function was that you could download
2028 * everything after a filter was applied; but this never really
2029 * took off. Instead, a select few people used this functionality
2030 * to download every available package on BaNaNaS. This is not in
2031 * the spirit of this service. Additionally, these few people were
2032 * good for 70% of the consumed bandwidth of BaNaNaS. */
2033 IConsolePrint(CC_ERROR, "'select all' is no longer supported since 1.11.");
2034 } else {
2035 _network_content_client.Select((ContentID)atoi(argv[2]));
2037 return true;
2040 if (StrEqualsIgnoreCase(argv[1], "unselect")) {
2041 if (argc <= 2) {
2042 IConsolePrint(CC_ERROR, "You must enter the id.");
2043 return false;
2045 if (StrEqualsIgnoreCase(argv[2], "all")) {
2046 _network_content_client.UnselectAll();
2047 } else {
2048 _network_content_client.Unselect((ContentID)atoi(argv[2]));
2050 return true;
2053 if (StrEqualsIgnoreCase(argv[1], "state")) {
2054 IConsolePrint(CC_WHITE, "id, type, state, name");
2055 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
2056 if (argc > 2 && strcasestr((*iter)->name.c_str(), argv[2]) == nullptr) continue;
2057 OutputContentState(*iter);
2059 return true;
2062 if (StrEqualsIgnoreCase(argv[1], "download")) {
2063 uint files;
2064 uint bytes;
2065 _network_content_client.DownloadSelectedContent(files, bytes);
2066 IConsolePrint(CC_DEFAULT, "Downloading {} file(s) ({} bytes).", files, bytes);
2067 return true;
2070 return false;
2072 #endif /* defined(WITH_ZLIB) */
2074 DEF_CONSOLE_CMD(ConFont)
2076 if (argc == 0) {
2077 IConsolePrint(CC_HELP, "Manage the fonts configuration.");
2078 IConsolePrint(CC_HELP, "Usage 'font'.");
2079 IConsolePrint(CC_HELP, " Print out the fonts configuration.");
2080 IConsolePrint(CC_HELP, "Usage 'font [medium|small|large|mono] [<name>] [<size>] [aa|noaa]'.");
2081 IConsolePrint(CC_HELP, " Change the configuration for a font.");
2082 IConsolePrint(CC_HELP, " Omitting an argument will keep the current value.");
2083 IConsolePrint(CC_HELP, " Set <name> to \"\" for the sprite font (size and aa have no effect on sprite font).");
2084 return true;
2087 FontSize argfs;
2088 for (argfs = FS_BEGIN; argfs < FS_END; argfs++) {
2089 if (argc > 1 && StrEqualsIgnoreCase(argv[1], FontSizeToName(argfs))) break;
2092 /* First argument must be a FontSize. */
2093 if (argc > 1 && argfs == FS_END) return false;
2095 if (argc > 2) {
2096 FontCacheSubSetting *setting = GetFontCacheSubSetting(argfs);
2097 std::string font = setting->font;
2098 uint size = setting->size;
2099 bool aa = setting->aa;
2101 byte arg_index = 2;
2102 /* We may encounter "aa" or "noaa" but it must be the last argument. */
2103 if (StrEqualsIgnoreCase(argv[arg_index], "aa") || StrEqualsIgnoreCase(argv[arg_index], "noaa")) {
2104 aa = !StrStartsWithIgnoreCase(argv[arg_index++], "no");
2105 if (argc > arg_index) return false;
2106 } else {
2107 /* For <name> we want a string. */
2108 uint v;
2109 if (!GetArgumentInteger(&v, argv[arg_index])) {
2110 font = argv[arg_index++];
2114 if (argc > arg_index) {
2115 /* For <size> we want a number. */
2116 uint v;
2117 if (GetArgumentInteger(&v, argv[arg_index])) {
2118 size = v;
2119 arg_index++;
2123 if (argc > arg_index) {
2124 /* Last argument must be "aa" or "noaa". */
2125 if (!StrEqualsIgnoreCase(argv[arg_index], "aa") && !StrEqualsIgnoreCase(argv[arg_index], "noaa")) return false;
2126 aa = !StrStartsWithIgnoreCase(argv[arg_index++], "no");
2127 if (argc > arg_index) return false;
2130 SetFont(argfs, font, size, aa);
2133 for (FontSize fs = FS_BEGIN; fs < FS_END; fs++) {
2134 FontCache *fc = FontCache::Get(fs);
2135 FontCacheSubSetting *setting = GetFontCacheSubSetting(fs);
2136 /* Make sure all non sprite fonts are loaded. */
2137 if (!setting->font.empty() && !fc->HasParent()) {
2138 InitFontCache(fs == FS_MONO);
2139 fc = FontCache::Get(fs);
2141 IConsolePrint(CC_DEFAULT, "{}: \"{}\" {} {} [\"{}\" {} {}]", FontSizeToName(fs), fc->GetFontName(), fc->GetFontSize(), GetFontAAState(fs) ? "aa" : "noaa", setting->font, setting->size, setting->aa ? "aa" : "noaa");
2144 return true;
2147 DEF_CONSOLE_CMD(ConSetting)
2149 if (argc == 0) {
2150 IConsolePrint(CC_HELP, "Change setting for all clients. Usage: 'setting <name> [<value>]'.");
2151 IConsolePrint(CC_HELP, "Omitting <value> will print out the current value of the setting.");
2152 return true;
2155 if (argc == 1 || argc > 3) return false;
2157 if (argc == 2) {
2158 IConsoleGetSetting(argv[1]);
2159 } else {
2160 IConsoleSetSetting(argv[1], argv[2]);
2163 return true;
2166 DEF_CONSOLE_CMD(ConSettingNewgame)
2168 if (argc == 0) {
2169 IConsolePrint(CC_HELP, "Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'.");
2170 IConsolePrint(CC_HELP, "Omitting <value> will print out the current value of the setting.");
2171 return true;
2174 if (argc == 1 || argc > 3) return false;
2176 if (argc == 2) {
2177 IConsoleGetSetting(argv[1], true);
2178 } else {
2179 IConsoleSetSetting(argv[1], argv[2], true);
2182 return true;
2185 DEF_CONSOLE_CMD(ConListSettings)
2187 if (argc == 0) {
2188 IConsolePrint(CC_HELP, "List settings. Usage: 'list_settings [<pre-filter>]'.");
2189 return true;
2192 if (argc > 2) return false;
2194 IConsoleListSettings((argc == 2) ? argv[1] : nullptr);
2195 return true;
2198 DEF_CONSOLE_CMD(ConGamelogPrint)
2200 if (argc == 0) {
2201 IConsolePrint(CC_HELP, "Print logged fundamental changes to the game since the start. Usage: 'gamelog'.");
2202 return true;
2205 _gamelog.PrintConsole();
2206 return true;
2209 DEF_CONSOLE_CMD(ConNewGRFReload)
2211 if (argc == 0) {
2212 IConsolePrint(CC_HELP, "Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
2213 return true;
2216 ReloadNewGRFData();
2217 return true;
2220 DEF_CONSOLE_CMD(ConListDirs)
2222 struct SubdirNameMap {
2223 Subdirectory subdir; ///< Index of subdirectory type
2224 const char *name; ///< UI name for the directory
2225 bool default_only; ///< Whether only the default (first existing) directory for this is interesting
2227 static const SubdirNameMap subdir_name_map[] = {
2228 /* Game data directories */
2229 { BASESET_DIR, "baseset", false },
2230 { NEWGRF_DIR, "newgrf", false },
2231 { AI_DIR, "ai", false },
2232 { AI_LIBRARY_DIR, "ailib", false },
2233 { GAME_DIR, "gs", false },
2234 { GAME_LIBRARY_DIR, "gslib", false },
2235 { SCENARIO_DIR, "scenario", false },
2236 { HEIGHTMAP_DIR, "heightmap", false },
2237 /* Default save locations for user data */
2238 { SAVE_DIR, "save", true },
2239 { AUTOSAVE_DIR, "autosave", true },
2240 { SCREENSHOT_DIR, "screenshot", true },
2241 { SOCIAL_INTEGRATION_DIR, "social_integration", true },
2244 if (argc != 2) {
2245 IConsolePrint(CC_HELP, "List all search paths or default directories for various categories.");
2246 IConsolePrint(CC_HELP, "Usage: list_dirs <category>");
2247 std::string cats = subdir_name_map[0].name;
2248 bool first = true;
2249 for (const SubdirNameMap &sdn : subdir_name_map) {
2250 if (!first) cats = cats + ", " + sdn.name;
2251 first = false;
2253 IConsolePrint(CC_HELP, "Valid categories: {}", cats);
2254 return true;
2257 std::set<std::string> seen_dirs;
2258 for (const SubdirNameMap &sdn : subdir_name_map) {
2259 if (!StrEqualsIgnoreCase(argv[1], sdn.name)) continue;
2260 bool found = false;
2261 for (Searchpath sp : _valid_searchpaths) {
2262 /* Get the directory */
2263 std::string path = FioGetDirectory(sp, sdn.subdir);
2264 /* Check it hasn't already been listed */
2265 if (seen_dirs.find(path) != seen_dirs.end()) continue;
2266 seen_dirs.insert(path);
2267 /* Check if exists and mark found */
2268 bool exists = FileExists(path);
2269 found |= exists;
2270 /* Print */
2271 if (!sdn.default_only || exists) {
2272 IConsolePrint(exists ? CC_DEFAULT : CC_INFO, "{} {}", path, exists ? "[ok]" : "[not found]");
2273 if (sdn.default_only) break;
2276 if (!found) {
2277 IConsolePrint(CC_ERROR, "No directories exist for category {}", argv[1]);
2279 return true;
2282 IConsolePrint(CC_ERROR, "Invalid category name: {}", argv[1]);
2283 return false;
2286 DEF_CONSOLE_CMD(ConNewGRFProfile)
2288 if (argc == 0) {
2289 IConsolePrint(CC_HELP, "Collect performance data about NewGRF sprite requests and callbacks. Sub-commands can be abbreviated.");
2290 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile [list]':");
2291 IConsolePrint(CC_HELP, " List all NewGRFs that can be profiled, and their status.");
2292 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile select <grf-num>...':");
2293 IConsolePrint(CC_HELP, " Select one or more GRFs for profiling.");
2294 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile unselect <grf-num>...':");
2295 IConsolePrint(CC_HELP, " Unselect one or more GRFs from profiling. Use the keyword \"all\" instead of a GRF number to unselect all. Removing an active profiler aborts data collection.");
2296 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile start [<num-ticks>]':");
2297 IConsolePrint(CC_HELP, " Begin profiling all selected GRFs. If a number of ticks is provided, profiling stops after that many game ticks. There are 74 ticks in a calendar day.");
2298 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile stop':");
2299 IConsolePrint(CC_HELP, " End profiling and write the collected data to CSV files.");
2300 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile abort':");
2301 IConsolePrint(CC_HELP, " End profiling and discard all collected data.");
2302 return true;
2305 const std::vector<GRFFile *> &files = GetAllGRFFiles();
2307 /* "list" sub-command */
2308 if (argc == 1 || StrStartsWithIgnoreCase(argv[1], "lis")) {
2309 IConsolePrint(CC_INFO, "Loaded GRF files:");
2310 int i = 1;
2311 for (GRFFile *grf : files) {
2312 auto profiler = std::find_if(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; });
2313 bool selected = profiler != _newgrf_profilers.end();
2314 bool active = selected && profiler->active;
2315 TextColour tc = active ? TC_LIGHT_BLUE : selected ? TC_GREEN : CC_INFO;
2316 const char *statustext = active ? " (active)" : selected ? " (selected)" : "";
2317 IConsolePrint(tc, "{}: [{:08X}] {}{}", i, BSWAP32(grf->grfid), grf->filename, statustext);
2318 i++;
2320 return true;
2323 /* "select" sub-command */
2324 if (StrStartsWithIgnoreCase(argv[1], "sel") && argc >= 3) {
2325 for (size_t argnum = 2; argnum < argc; ++argnum) {
2326 int grfnum = atoi(argv[argnum]);
2327 if (grfnum < 1 || grfnum > (int)files.size()) { // safe cast, files.size() should not be larger than a few hundred in the most extreme cases
2328 IConsolePrint(CC_WARNING, "GRF number {} out of range, not added.", grfnum);
2329 continue;
2331 GRFFile *grf = files[grfnum - 1];
2332 if (std::any_of(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; })) {
2333 IConsolePrint(CC_WARNING, "GRF number {} [{:08X}] is already selected for profiling.", grfnum, BSWAP32(grf->grfid));
2334 continue;
2336 _newgrf_profilers.emplace_back(grf);
2338 return true;
2341 /* "unselect" sub-command */
2342 if (StrStartsWithIgnoreCase(argv[1], "uns") && argc >= 3) {
2343 for (size_t argnum = 2; argnum < argc; ++argnum) {
2344 if (StrEqualsIgnoreCase(argv[argnum], "all")) {
2345 _newgrf_profilers.clear();
2346 break;
2348 int grfnum = atoi(argv[argnum]);
2349 if (grfnum < 1 || grfnum > (int)files.size()) {
2350 IConsolePrint(CC_WARNING, "GRF number {} out of range, not removing.", grfnum);
2351 continue;
2353 GRFFile *grf = files[grfnum - 1];
2354 auto pos = std::find_if(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; });
2355 if (pos != _newgrf_profilers.end()) _newgrf_profilers.erase(pos);
2357 return true;
2360 /* "start" sub-command */
2361 if (StrStartsWithIgnoreCase(argv[1], "sta")) {
2362 std::string grfids;
2363 size_t started = 0;
2364 for (NewGRFProfiler &pr : _newgrf_profilers) {
2365 if (!pr.active) {
2366 pr.Start();
2367 started++;
2369 if (!grfids.empty()) grfids += ", ";
2370 fmt::format_to(std::back_inserter(grfids), "[{:08X}]", BSWAP32(pr.grffile->grfid));
2373 if (started > 0) {
2374 IConsolePrint(CC_DEBUG, "Started profiling for GRFID{} {}.", (started > 1) ? "s" : "", grfids);
2376 if (argc >= 3) {
2377 uint64_t ticks = std::max(atoi(argv[2]), 1);
2378 NewGRFProfiler::StartTimer(ticks);
2379 IConsolePrint(CC_DEBUG, "Profiling will automatically stop after {} ticks.", ticks);
2381 } else if (_newgrf_profilers.empty()) {
2382 IConsolePrint(CC_ERROR, "No GRFs selected for profiling, did not start.");
2383 } else {
2384 IConsolePrint(CC_ERROR, "Did not start profiling for any GRFs, all selected GRFs are already profiling.");
2386 return true;
2389 /* "stop" sub-command */
2390 if (StrStartsWithIgnoreCase(argv[1], "sto")) {
2391 NewGRFProfiler::FinishAll();
2392 return true;
2395 /* "abort" sub-command */
2396 if (StrStartsWithIgnoreCase(argv[1], "abo")) {
2397 for (NewGRFProfiler &pr : _newgrf_profilers) {
2398 pr.Abort();
2400 NewGRFProfiler::AbortTimer();
2401 return true;
2404 return false;
2407 #ifdef _DEBUG
2408 /******************
2409 * debug commands
2410 ******************/
2412 static void IConsoleDebugLibRegister()
2414 IConsole::CmdRegister("resettile", ConResetTile);
2415 IConsole::AliasRegister("dbg_echo", "echo %A; echo %B");
2416 IConsole::AliasRegister("dbg_echo2", "echo %!");
2418 #endif
2420 DEF_CONSOLE_CMD(ConFramerate)
2422 if (argc == 0) {
2423 IConsolePrint(CC_HELP, "Show frame rate and game speed information.");
2424 return true;
2427 ConPrintFramerate();
2428 return true;
2431 DEF_CONSOLE_CMD(ConFramerateWindow)
2433 if (argc == 0) {
2434 IConsolePrint(CC_HELP, "Open the frame rate window.");
2435 return true;
2438 if (_network_dedicated) {
2439 IConsolePrint(CC_ERROR, "Can not open frame rate window on a dedicated server.");
2440 return false;
2443 ShowFramerateWindow();
2444 return true;
2447 static void ConDumpRoadTypes()
2449 IConsolePrint(CC_DEFAULT, " Flags:");
2450 IConsolePrint(CC_DEFAULT, " c = catenary");
2451 IConsolePrint(CC_DEFAULT, " l = no level crossings");
2452 IConsolePrint(CC_DEFAULT, " X = no houses");
2453 IConsolePrint(CC_DEFAULT, " h = hidden");
2454 IConsolePrint(CC_DEFAULT, " T = buildable by towns");
2456 std::map<uint32_t, const GRFFile *> grfs;
2457 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
2458 const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
2459 if (rti->label == 0) continue;
2460 uint32_t grfid = 0;
2461 const GRFFile *grf = rti->grffile[ROTSG_GROUND];
2462 if (grf != nullptr) {
2463 grfid = grf->grfid;
2464 grfs.emplace(grfid, grf);
2466 IConsolePrint(CC_DEFAULT, " {:02d} {} {:c}{:c}{:c}{:c}, Flags: {}{}{}{}{}, GRF: {:08X}, {}",
2467 (uint)rt,
2468 RoadTypeIsTram(rt) ? "Tram" : "Road",
2469 rti->label >> 24, rti->label >> 16, rti->label >> 8, rti->label,
2470 HasBit(rti->flags, ROTF_CATENARY) ? 'c' : '-',
2471 HasBit(rti->flags, ROTF_NO_LEVEL_CROSSING) ? 'l' : '-',
2472 HasBit(rti->flags, ROTF_NO_HOUSES) ? 'X' : '-',
2473 HasBit(rti->flags, ROTF_HIDDEN) ? 'h' : '-',
2474 HasBit(rti->flags, ROTF_TOWN_BUILD) ? 'T' : '-',
2475 BSWAP32(grfid),
2476 GetStringPtr(rti->strings.name)
2479 for (const auto &grf : grfs) {
2480 IConsolePrint(CC_DEFAULT, " GRF: {:08X} = {}", BSWAP32(grf.first), grf.second->filename);
2484 static void ConDumpRailTypes()
2486 IConsolePrint(CC_DEFAULT, " Flags:");
2487 IConsolePrint(CC_DEFAULT, " c = catenary");
2488 IConsolePrint(CC_DEFAULT, " l = no level crossings");
2489 IConsolePrint(CC_DEFAULT, " h = hidden");
2490 IConsolePrint(CC_DEFAULT, " s = no sprite combine");
2491 IConsolePrint(CC_DEFAULT, " a = always allow 90 degree turns");
2492 IConsolePrint(CC_DEFAULT, " d = always disallow 90 degree turns");
2494 std::map<uint32_t, const GRFFile *> grfs;
2495 for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
2496 const RailTypeInfo *rti = GetRailTypeInfo(rt);
2497 if (rti->label == 0) continue;
2498 uint32_t grfid = 0;
2499 const GRFFile *grf = rti->grffile[RTSG_GROUND];
2500 if (grf != nullptr) {
2501 grfid = grf->grfid;
2502 grfs.emplace(grfid, grf);
2504 IConsolePrint(CC_DEFAULT, " {:02d} {:c}{:c}{:c}{:c}, Flags: {}{}{}{}{}{}, GRF: {:08X}, {}",
2505 (uint)rt,
2506 rti->label >> 24, rti->label >> 16, rti->label >> 8, rti->label,
2507 HasBit(rti->flags, RTF_CATENARY) ? 'c' : '-',
2508 HasBit(rti->flags, RTF_NO_LEVEL_CROSSING) ? 'l' : '-',
2509 HasBit(rti->flags, RTF_HIDDEN) ? 'h' : '-',
2510 HasBit(rti->flags, RTF_NO_SPRITE_COMBINE) ? 's' : '-',
2511 HasBit(rti->flags, RTF_ALLOW_90DEG) ? 'a' : '-',
2512 HasBit(rti->flags, RTF_DISALLOW_90DEG) ? 'd' : '-',
2513 BSWAP32(grfid),
2514 GetStringPtr(rti->strings.name)
2517 for (const auto &grf : grfs) {
2518 IConsolePrint(CC_DEFAULT, " GRF: {:08X} = {}", BSWAP32(grf.first), grf.second->filename);
2522 static void ConDumpCargoTypes()
2524 IConsolePrint(CC_DEFAULT, " Cargo classes:");
2525 IConsolePrint(CC_DEFAULT, " p = passenger");
2526 IConsolePrint(CC_DEFAULT, " m = mail");
2527 IConsolePrint(CC_DEFAULT, " x = express");
2528 IConsolePrint(CC_DEFAULT, " a = armoured");
2529 IConsolePrint(CC_DEFAULT, " b = bulk");
2530 IConsolePrint(CC_DEFAULT, " g = piece goods");
2531 IConsolePrint(CC_DEFAULT, " l = liquid");
2532 IConsolePrint(CC_DEFAULT, " r = refrigerated");
2533 IConsolePrint(CC_DEFAULT, " h = hazardous");
2534 IConsolePrint(CC_DEFAULT, " c = covered/sheltered");
2535 IConsolePrint(CC_DEFAULT, " S = special");
2537 std::map<uint32_t, const GRFFile *> grfs;
2538 for (const CargoSpec *spec : CargoSpec::Iterate()) {
2539 if (!spec->IsValid()) continue;
2540 uint32_t grfid = 0;
2541 const GRFFile *grf = spec->grffile;
2542 if (grf != nullptr) {
2543 grfid = grf->grfid;
2544 grfs.emplace(grfid, grf);
2546 IConsolePrint(CC_DEFAULT, " {:02d} Bit: {:2d}, Label: {:c}{:c}{:c}{:c}, Callback mask: 0x{:02X}, Cargo class: {}{}{}{}{}{}{}{}{}{}{}, GRF: {:08X}, {}",
2547 spec->Index(),
2548 spec->bitnum,
2549 spec->label.base() >> 24, spec->label.base() >> 16, spec->label.base() >> 8, spec->label.base(),
2550 spec->callback_mask,
2551 (spec->classes & CC_PASSENGERS) != 0 ? 'p' : '-',
2552 (spec->classes & CC_MAIL) != 0 ? 'm' : '-',
2553 (spec->classes & CC_EXPRESS) != 0 ? 'x' : '-',
2554 (spec->classes & CC_ARMOURED) != 0 ? 'a' : '-',
2555 (spec->classes & CC_BULK) != 0 ? 'b' : '-',
2556 (spec->classes & CC_PIECE_GOODS) != 0 ? 'g' : '-',
2557 (spec->classes & CC_LIQUID) != 0 ? 'l' : '-',
2558 (spec->classes & CC_REFRIGERATED) != 0 ? 'r' : '-',
2559 (spec->classes & CC_HAZARDOUS) != 0 ? 'h' : '-',
2560 (spec->classes & CC_COVERED) != 0 ? 'c' : '-',
2561 (spec->classes & CC_SPECIAL) != 0 ? 'S' : '-',
2562 BSWAP32(grfid),
2563 GetStringPtr(spec->name)
2566 for (const auto &grf : grfs) {
2567 IConsolePrint(CC_DEFAULT, " GRF: {:08X} = {}", BSWAP32(grf.first), grf.second->filename);
2572 DEF_CONSOLE_CMD(ConDumpInfo)
2574 if (argc != 2) {
2575 IConsolePrint(CC_HELP, "Dump debugging information.");
2576 IConsolePrint(CC_HELP, "Usage: 'dump_info roadtypes|railtypes|cargotypes'.");
2577 IConsolePrint(CC_HELP, " Show information about road/tram types, rail types or cargo types.");
2578 return true;
2581 if (StrEqualsIgnoreCase(argv[1], "roadtypes")) {
2582 ConDumpRoadTypes();
2583 return true;
2586 if (StrEqualsIgnoreCase(argv[1], "railtypes")) {
2587 ConDumpRailTypes();
2588 return true;
2591 if (StrEqualsIgnoreCase(argv[1], "cargotypes")) {
2592 ConDumpCargoTypes();
2593 return true;
2596 return false;
2599 /*******************************
2600 * console command registration
2601 *******************************/
2603 void IConsoleStdLibRegister()
2605 IConsole::CmdRegister("debug_level", ConDebugLevel);
2606 IConsole::CmdRegister("echo", ConEcho);
2607 IConsole::CmdRegister("echoc", ConEchoC);
2608 IConsole::CmdRegister("exec", ConExec);
2609 IConsole::CmdRegister("exit", ConExit);
2610 IConsole::CmdRegister("part", ConPart);
2611 IConsole::CmdRegister("help", ConHelp);
2612 IConsole::CmdRegister("info_cmd", ConInfoCmd);
2613 IConsole::CmdRegister("list_cmds", ConListCommands);
2614 IConsole::CmdRegister("list_aliases", ConListAliases);
2615 IConsole::CmdRegister("newgame", ConNewGame);
2616 IConsole::CmdRegister("restart", ConRestart);
2617 IConsole::CmdRegister("reload", ConReload);
2618 IConsole::CmdRegister("getseed", ConGetSeed);
2619 IConsole::CmdRegister("getdate", ConGetDate);
2620 IConsole::CmdRegister("getsysdate", ConGetSysDate);
2621 IConsole::CmdRegister("quit", ConExit);
2622 IConsole::CmdRegister("resetengines", ConResetEngines, ConHookNoNetwork);
2623 IConsole::CmdRegister("reset_enginepool", ConResetEnginePool, ConHookNoNetwork);
2624 IConsole::CmdRegister("return", ConReturn);
2625 IConsole::CmdRegister("screenshot", ConScreenShot);
2626 IConsole::CmdRegister("script", ConScript);
2627 IConsole::CmdRegister("zoomto", ConZoomToLevel);
2628 IConsole::CmdRegister("scrollto", ConScrollToTile);
2629 IConsole::CmdRegister("alias", ConAlias);
2630 IConsole::CmdRegister("load", ConLoad);
2631 IConsole::CmdRegister("load_save", ConLoad);
2632 IConsole::CmdRegister("load_scenario", ConLoadScenario);
2633 IConsole::CmdRegister("load_heightmap", ConLoadHeightmap);
2634 IConsole::CmdRegister("rm", ConRemove);
2635 IConsole::CmdRegister("save", ConSave);
2636 IConsole::CmdRegister("saveconfig", ConSaveConfig);
2637 IConsole::CmdRegister("ls", ConListFiles);
2638 IConsole::CmdRegister("list_saves", ConListFiles);
2639 IConsole::CmdRegister("list_scenarios", ConListScenarios);
2640 IConsole::CmdRegister("list_heightmaps", ConListHeightmaps);
2641 IConsole::CmdRegister("cd", ConChangeDirectory);
2642 IConsole::CmdRegister("pwd", ConPrintWorkingDirectory);
2643 IConsole::CmdRegister("clear", ConClearBuffer);
2644 IConsole::CmdRegister("font", ConFont);
2645 IConsole::CmdRegister("setting", ConSetting);
2646 IConsole::CmdRegister("setting_newgame", ConSettingNewgame);
2647 IConsole::CmdRegister("list_settings", ConListSettings);
2648 IConsole::CmdRegister("gamelog", ConGamelogPrint);
2649 IConsole::CmdRegister("rescan_newgrf", ConRescanNewGRF);
2650 IConsole::CmdRegister("list_dirs", ConListDirs);
2652 IConsole::AliasRegister("dir", "ls");
2653 IConsole::AliasRegister("del", "rm %+");
2654 IConsole::AliasRegister("newmap", "newgame");
2655 IConsole::AliasRegister("patch", "setting %+");
2656 IConsole::AliasRegister("set", "setting %+");
2657 IConsole::AliasRegister("set_newgame", "setting_newgame %+");
2658 IConsole::AliasRegister("list_patches", "list_settings %+");
2659 IConsole::AliasRegister("developer", "setting developer %+");
2661 IConsole::CmdRegister("list_ai_libs", ConListAILibs);
2662 IConsole::CmdRegister("list_ai", ConListAI);
2663 IConsole::CmdRegister("reload_ai", ConReloadAI);
2664 IConsole::CmdRegister("rescan_ai", ConRescanAI);
2665 IConsole::CmdRegister("start_ai", ConStartAI);
2666 IConsole::CmdRegister("stop_ai", ConStopAI);
2668 IConsole::CmdRegister("list_game", ConListGame);
2669 IConsole::CmdRegister("list_game_libs", ConListGameLibs);
2670 IConsole::CmdRegister("rescan_game", ConRescanGame);
2672 IConsole::CmdRegister("companies", ConCompanies);
2673 IConsole::AliasRegister("players", "companies");
2675 /* networking functions */
2677 /* Content downloading is only available with ZLIB */
2678 #if defined(WITH_ZLIB)
2679 IConsole::CmdRegister("content", ConContent);
2680 #endif /* defined(WITH_ZLIB) */
2682 /*** Networking commands ***/
2683 IConsole::CmdRegister("say", ConSay, ConHookNeedNetwork);
2684 IConsole::CmdRegister("say_company", ConSayCompany, ConHookNeedNetwork);
2685 IConsole::AliasRegister("say_player", "say_company %+");
2686 IConsole::CmdRegister("say_client", ConSayClient, ConHookNeedNetwork);
2688 IConsole::CmdRegister("connect", ConNetworkConnect, ConHookClientOnly);
2689 IConsole::CmdRegister("clients", ConNetworkClients, ConHookNeedNetwork);
2690 IConsole::CmdRegister("status", ConStatus, ConHookServerOnly);
2691 IConsole::CmdRegister("server_info", ConServerInfo, ConHookServerOnly);
2692 IConsole::AliasRegister("info", "server_info");
2693 IConsole::CmdRegister("reconnect", ConNetworkReconnect, ConHookClientOnly);
2694 IConsole::CmdRegister("rcon", ConRcon, ConHookNeedNetwork);
2696 IConsole::CmdRegister("join", ConJoinCompany, ConHookNeedNetwork);
2697 IConsole::AliasRegister("spectate", "join 255");
2698 IConsole::CmdRegister("move", ConMoveClient, ConHookServerOnly);
2699 IConsole::CmdRegister("reset_company", ConResetCompany, ConHookServerOnly);
2700 IConsole::AliasRegister("clean_company", "reset_company %A");
2701 IConsole::CmdRegister("client_name", ConClientNickChange, ConHookServerOnly);
2702 IConsole::CmdRegister("kick", ConKick, ConHookServerOnly);
2703 IConsole::CmdRegister("ban", ConBan, ConHookServerOnly);
2704 IConsole::CmdRegister("unban", ConUnBan, ConHookServerOnly);
2705 IConsole::CmdRegister("banlist", ConBanList, ConHookServerOnly);
2707 IConsole::CmdRegister("pause", ConPauseGame, ConHookServerOrNoNetwork);
2708 IConsole::CmdRegister("unpause", ConUnpauseGame, ConHookServerOrNoNetwork);
2710 IConsole::CmdRegister("company_pw", ConCompanyPassword, ConHookNeedNetwork);
2711 IConsole::AliasRegister("company_password", "company_pw %+");
2713 IConsole::AliasRegister("net_frame_freq", "setting frame_freq %+");
2714 IConsole::AliasRegister("net_sync_freq", "setting sync_freq %+");
2715 IConsole::AliasRegister("server_pw", "setting server_password %+");
2716 IConsole::AliasRegister("server_password", "setting server_password %+");
2717 IConsole::AliasRegister("rcon_pw", "setting rcon_password %+");
2718 IConsole::AliasRegister("rcon_password", "setting rcon_password %+");
2719 IConsole::AliasRegister("name", "setting client_name %+");
2720 IConsole::AliasRegister("server_name", "setting server_name %+");
2721 IConsole::AliasRegister("server_port", "setting server_port %+");
2722 IConsole::AliasRegister("max_clients", "setting max_clients %+");
2723 IConsole::AliasRegister("max_companies", "setting max_companies %+");
2724 IConsole::AliasRegister("max_join_time", "setting max_join_time %+");
2725 IConsole::AliasRegister("pause_on_join", "setting pause_on_join %+");
2726 IConsole::AliasRegister("autoclean_companies", "setting autoclean_companies %+");
2727 IConsole::AliasRegister("autoclean_protected", "setting autoclean_protected %+");
2728 IConsole::AliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2729 IConsole::AliasRegister("restart_game_year", "setting restart_game_year %+");
2730 IConsole::AliasRegister("min_players", "setting min_active_clients %+");
2731 IConsole::AliasRegister("reload_cfg", "setting reload_cfg %+");
2733 /* debugging stuff */
2734 #ifdef _DEBUG
2735 IConsoleDebugLibRegister();
2736 #endif
2737 IConsole::CmdRegister("fps", ConFramerate);
2738 IConsole::CmdRegister("fps_wnd", ConFramerateWindow);
2740 /* NewGRF development stuff */
2741 IConsole::CmdRegister("reload_newgrfs", ConNewGRFReload, ConHookNewGRFDeveloperTool);
2742 IConsole::CmdRegister("newgrf_profile", ConNewGRFProfile, ConHookNewGRFDeveloperTool);
2744 IConsole::CmdRegister("dump_info", ConDumpInfo);