Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / console_cmds.cpp
blob8963c47517d6c80d0137ab2883e2a21e042f5d46
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/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 "screenshot.h"
27 #include "genworld.h"
28 #include "strings_func.h"
29 #include "viewport_func.h"
30 #include "window_func.h"
31 #include "date_func.h"
32 #include "company_func.h"
33 #include "gamelog.h"
34 #include "ai/ai.hpp"
35 #include "ai/ai_config.hpp"
36 #include "newgrf.h"
37 #include "newgrf_profiling.h"
38 #include "console_func.h"
39 #include "engine_base.h"
40 #include "road.h"
41 #include "rail.h"
42 #include "game/game.hpp"
43 #include "table/strings.h"
44 #include "walltime_func.h"
46 #include "safeguards.h"
48 /* scriptfile handling */
49 static uint _script_current_depth; ///< Depth of scripts running (used to abort execution when #ConReturn is encountered).
51 /** File list storage for the console, for caching the last 'ls' command. */
52 class ConsoleFileList : public FileList {
53 public:
54 ConsoleFileList() : FileList()
56 this->file_list_valid = false;
59 /** Declare the file storage cache as being invalid, also clears all stored files. */
60 void InvalidateFileList()
62 this->clear();
63 this->file_list_valid = false;
66 /**
67 * (Re-)validate the file storage cache. Only makes a change if the storage was invalid, or if \a force_reload.
68 * @param force_reload Always reload the file storage cache.
70 void ValidateFileList(bool force_reload = false)
72 if (force_reload || !this->file_list_valid) {
73 this->BuildFileList(FT_SAVEGAME, SLO_LOAD);
74 this->file_list_valid = true;
78 bool file_list_valid; ///< If set, the file list is valid.
81 static ConsoleFileList _console_file_list; ///< File storage cache for the console.
83 /* console command defines */
84 #define DEF_CONSOLE_CMD(function) static bool function(byte argc, char *argv[])
85 #define DEF_CONSOLE_HOOK(function) static ConsoleHookResult function(bool echo)
88 /****************
89 * command hooks
90 ****************/
92 /**
93 * Check network availability and inform in console about failure of detection.
94 * @return Network availability.
96 static inline bool NetworkAvailable(bool echo)
98 if (!_network_available) {
99 if (echo) IConsolePrint(CC_ERROR, "You cannot use this command because there is no network available.");
100 return false;
102 return true;
106 * Check whether we are a server.
107 * @return Are we a server? True when yes, false otherwise.
109 DEF_CONSOLE_HOOK(ConHookServerOnly)
111 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
113 if (!_network_server) {
114 if (echo) IConsolePrint(CC_ERROR, "This command is only available to a network server.");
115 return CHR_DISALLOW;
117 return CHR_ALLOW;
121 * Check whether we are a client in a network game.
122 * @return Are we a client in a network game? True when yes, false otherwise.
124 DEF_CONSOLE_HOOK(ConHookClientOnly)
126 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
128 if (_network_server) {
129 if (echo) IConsolePrint(CC_ERROR, "This command is not available to a network server.");
130 return CHR_DISALLOW;
132 return CHR_ALLOW;
136 * Check whether we are in a multiplayer game.
137 * @return True when we are client or server in a network game.
139 DEF_CONSOLE_HOOK(ConHookNeedNetwork)
141 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
143 if (!_networking || (!_network_server && !MyClient::IsConnected())) {
144 if (echo) IConsolePrint(CC_ERROR, "Not connected. This command is only available in multiplayer.");
145 return CHR_DISALLOW;
147 return CHR_ALLOW;
151 * Check whether we are in singleplayer mode.
152 * @return True when no network is active.
154 DEF_CONSOLE_HOOK(ConHookNoNetwork)
156 if (_networking) {
157 if (echo) IConsolePrint(CC_ERROR, "This command is forbidden in multiplayer.");
158 return CHR_DISALLOW;
160 return CHR_ALLOW;
164 * Check if are either in singleplayer or a server.
165 * @return True iff we are either in singleplayer or a server.
167 DEF_CONSOLE_HOOK(ConHookServerOrNoNetwork)
169 if (_networking && !_network_server) {
170 if (echo) IConsolePrint(CC_ERROR, "This command is only available to a network server.");
171 return CHR_DISALLOW;
173 return CHR_ALLOW;
176 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool)
178 if (_settings_client.gui.newgrf_developer_tools) {
179 if (_game_mode == GM_MENU) {
180 if (echo) IConsolePrint(CC_ERROR, "This command is only available in-game and in the editor.");
181 return CHR_DISALLOW;
183 return ConHookNoNetwork(echo);
185 return CHR_HIDE;
189 * Reset status of all engines.
190 * @return Will always succeed.
192 DEF_CONSOLE_CMD(ConResetEngines)
194 if (argc == 0) {
195 IConsolePrint(CC_HELP, "Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'.");
196 return true;
199 StartupEngines();
200 return true;
204 * Reset status of the engine pool.
205 * @return Will always return true.
206 * @note Resetting the pool only succeeds when there are no vehicles ingame.
208 DEF_CONSOLE_CMD(ConResetEnginePool)
210 if (argc == 0) {
211 IConsolePrint(CC_HELP, "Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
212 return true;
215 if (_game_mode == GM_MENU) {
216 IConsolePrint(CC_ERROR, "This command is only available in-game and in the editor.");
217 return true;
220 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
221 IConsolePrint(CC_ERROR, "This can only be done when there are no vehicles in the game.");
222 return true;
225 return true;
228 #ifdef _DEBUG
230 * Reset a tile to bare land in debug mode.
231 * param tile number.
232 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
234 DEF_CONSOLE_CMD(ConResetTile)
236 if (argc == 0) {
237 IConsolePrint(CC_HELP, "Reset a tile to bare land. Usage: 'resettile <tile>'.");
238 IConsolePrint(CC_HELP, "Tile can be either decimal (34161) or hexadecimal (0x4a5B).");
239 return true;
242 if (argc == 2) {
243 uint32 result;
244 if (GetArgumentInteger(&result, argv[1])) {
245 DoClearSquare((TileIndex)result);
246 return true;
250 return false;
252 #endif /* _DEBUG */
255 * Scroll to a tile on the map.
256 * param x tile number or tile x coordinate.
257 * param y optional y coordinate.
258 * @note When only one argument is given it is interpreted as the tile number.
259 * When two arguments are given, they are interpreted as the tile's x
260 * and y coordinates.
261 * @return True when either console help was shown or a proper amount of parameters given.
263 DEF_CONSOLE_CMD(ConScrollToTile)
265 switch (argc) {
266 case 0:
267 IConsolePrint(CC_HELP, "Center the screen on a given tile.");
268 IConsolePrint(CC_HELP, "Usage: 'scrollto <tile>' or 'scrollto <x> <y>'.");
269 IConsolePrint(CC_HELP, "Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
270 return true;
272 case 2: {
273 uint32 result;
274 if (GetArgumentInteger(&result, argv[1])) {
275 if (result >= MapSize()) {
276 IConsolePrint(CC_ERROR, "Tile does not exist.");
277 return true;
279 ScrollMainWindowToTile((TileIndex)result);
280 return true;
282 break;
285 case 3: {
286 uint32 x, y;
287 if (GetArgumentInteger(&x, argv[1]) && GetArgumentInteger(&y, argv[2])) {
288 if (x >= MapSizeX() || y >= MapSizeY()) {
289 IConsolePrint(CC_ERROR, "Tile does not exist.");
290 return true;
292 ScrollMainWindowToTile(TileXY(x, y));
293 return true;
295 break;
299 return false;
303 * Save the map to a file.
304 * param filename the filename to save the map to.
305 * @return True when help was displayed or the file attempted to be saved.
307 DEF_CONSOLE_CMD(ConSave)
309 if (argc == 0) {
310 IConsolePrint(CC_HELP, "Save the current game. Usage: 'save <filename>'.");
311 return true;
314 if (argc == 2) {
315 char *filename = str_fmt("%s.sav", argv[1]);
316 IConsolePrint(CC_DEFAULT, "Saving map...");
318 if (SaveOrLoad(filename, SLO_SAVE, DFT_GAME_FILE, SAVE_DIR) != SL_OK) {
319 IConsolePrint(CC_ERROR, "Saving map failed.");
320 } else {
321 IConsolePrint(CC_INFO, "Map successfully saved to '{}'.", filename);
323 free(filename);
324 return true;
327 return false;
331 * Explicitly save the configuration.
332 * @return True.
334 DEF_CONSOLE_CMD(ConSaveConfig)
336 if (argc == 0) {
337 IConsolePrint(CC_HELP, "Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
338 IConsolePrint(CC_HELP, "It does not save the configuration of the current game to the configuration file.");
339 return true;
342 SaveToConfig();
343 IConsolePrint(CC_DEFAULT, "Saved config.");
344 return true;
347 DEF_CONSOLE_CMD(ConLoad)
349 if (argc == 0) {
350 IConsolePrint(CC_HELP, "Load a game by name or index. Usage: 'load <file | number>'.");
351 return true;
354 if (argc != 2) return false;
356 const char *file = argv[1];
357 _console_file_list.ValidateFileList();
358 const FiosItem *item = _console_file_list.FindItem(file);
359 if (item != nullptr) {
360 if (GetAbstractFileType(item->type) == FT_SAVEGAME) {
361 _switch_mode = SM_LOAD_GAME;
362 _file_to_saveload.SetMode(item->type);
363 _file_to_saveload.SetName(FiosBrowseTo(item));
364 _file_to_saveload.SetTitle(item->title);
365 } else {
366 IConsolePrint(CC_ERROR, "'{}' is not a savegame.", file);
368 } else {
369 IConsolePrint(CC_ERROR, "'{}' cannot be found.", file);
372 return true;
376 DEF_CONSOLE_CMD(ConRemove)
378 if (argc == 0) {
379 IConsolePrint(CC_HELP, "Remove a savegame by name or index. Usage: 'rm <file | number>'.");
380 return true;
383 if (argc != 2) return false;
385 const char *file = argv[1];
386 _console_file_list.ValidateFileList();
387 const FiosItem *item = _console_file_list.FindItem(file);
388 if (item != nullptr) {
389 if (!FiosDelete(item->name)) {
390 IConsolePrint(CC_ERROR, "Failed to delete '{}'.", file);
392 } else {
393 IConsolePrint(CC_ERROR, "'{}' could not be found.", file);
396 _console_file_list.InvalidateFileList();
397 return true;
401 /* List all the files in the current dir via console */
402 DEF_CONSOLE_CMD(ConListFiles)
404 if (argc == 0) {
405 IConsolePrint(CC_HELP, "List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'.");
406 return true;
409 _console_file_list.ValidateFileList(true);
410 for (uint i = 0; i < _console_file_list.size(); i++) {
411 IConsolePrint(CC_DEFAULT, "{}) {}", i, _console_file_list[i].title);
414 return true;
417 /* Change the dir via console */
418 DEF_CONSOLE_CMD(ConChangeDirectory)
420 if (argc == 0) {
421 IConsolePrint(CC_HELP, "Change the dir via console. Usage: 'cd <directory | number>'.");
422 return true;
425 if (argc != 2) return false;
427 const char *file = argv[1];
428 _console_file_list.ValidateFileList(true);
429 const FiosItem *item = _console_file_list.FindItem(file);
430 if (item != nullptr) {
431 switch (item->type) {
432 case FIOS_TYPE_DIR: case FIOS_TYPE_DRIVE: case FIOS_TYPE_PARENT:
433 FiosBrowseTo(item);
434 break;
435 default: IConsolePrint(CC_ERROR, "{}: Not a directory.", file);
437 } else {
438 IConsolePrint(CC_ERROR, "{}: No such file or directory.", file);
441 _console_file_list.InvalidateFileList();
442 return true;
445 DEF_CONSOLE_CMD(ConPrintWorkingDirectory)
447 const char *path;
449 if (argc == 0) {
450 IConsolePrint(CC_HELP, "Print out the current working directory. Usage: 'pwd'.");
451 return true;
454 /* XXX - Workaround for broken file handling */
455 _console_file_list.ValidateFileList(true);
456 _console_file_list.InvalidateFileList();
458 FiosGetDescText(&path, nullptr);
459 IConsolePrint(CC_DEFAULT, path);
460 return true;
463 DEF_CONSOLE_CMD(ConClearBuffer)
465 if (argc == 0) {
466 IConsolePrint(CC_HELP, "Clear the console buffer. Usage: 'clear'.");
467 return true;
470 IConsoleClearBuffer();
471 SetWindowDirty(WC_CONSOLE, 0);
472 return true;
476 /**********************************
477 * Network Core Console Commands
478 **********************************/
480 static bool ConKickOrBan(const char *argv, bool ban, const std::string &reason)
482 uint n;
484 if (strchr(argv, '.') == nullptr && strchr(argv, ':') == nullptr) { // banning with ID
485 ClientID client_id = (ClientID)atoi(argv);
487 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
488 * kicking frees closes and subsequently free the connection related instances, which we
489 * would be reading from and writing to after returning. So we would read or write data
490 * from freed memory up till the segfault triggers. */
491 if (client_id == CLIENT_ID_SERVER || client_id == _redirect_console_to_client) {
492 IConsolePrint(CC_ERROR, "You can not {} yourself!", ban ? "ban" : "kick");
493 return true;
496 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
497 if (ci == nullptr) {
498 IConsolePrint(CC_ERROR, "Invalid client ID.");
499 return true;
502 if (!ban) {
503 /* Kick only this client, not all clients with that IP */
504 NetworkServerKickClient(client_id, reason);
505 return true;
508 /* When banning, kick+ban all clients with that IP */
509 n = NetworkServerKickOrBanIP(client_id, ban, reason);
510 } else {
511 n = NetworkServerKickOrBanIP(argv, ban, reason);
514 if (n == 0) {
515 IConsolePrint(CC_DEFAULT, ban ? "Client not online, address added to banlist." : "Client not found.");
516 } else {
517 IConsolePrint(CC_DEFAULT, "{}ed {} client(s).", ban ? "Bann" : "Kick", n);
520 return true;
523 DEF_CONSOLE_CMD(ConKick)
525 if (argc == 0) {
526 IConsolePrint(CC_HELP, "Kick a client from a network game. Usage: 'kick <ip | client-id> [<kick-reason>]'.");
527 IConsolePrint(CC_HELP, "For client-id's, see the command 'clients'.");
528 return true;
531 if (argc != 2 && argc != 3) return false;
533 /* No reason supplied for kicking */
534 if (argc == 2) return ConKickOrBan(argv[1], false, {});
536 /* Reason for kicking supplied */
537 size_t kick_message_length = strlen(argv[2]);
538 if (kick_message_length >= 255) {
539 IConsolePrint(CC_ERROR, "Maximum kick message length is 254 characters. You entered {} characters.", kick_message_length);
540 return false;
541 } else {
542 return ConKickOrBan(argv[1], false, argv[2]);
546 DEF_CONSOLE_CMD(ConBan)
548 if (argc == 0) {
549 IConsolePrint(CC_HELP, "Ban a client from a network game. Usage: 'ban <ip | client-id> [<ban-reason>]'.");
550 IConsolePrint(CC_HELP, "For client-id's, see the command 'clients'.");
551 IConsolePrint(CC_HELP, "If the client is no longer online, you can still ban their IP.");
552 return true;
555 if (argc != 2 && argc != 3) return false;
557 /* No reason supplied for kicking */
558 if (argc == 2) return ConKickOrBan(argv[1], true, {});
560 /* Reason for kicking supplied */
561 size_t kick_message_length = strlen(argv[2]);
562 if (kick_message_length >= 255) {
563 IConsolePrint(CC_ERROR, "Maximum kick message length is 254 characters. You entered {} characters.", kick_message_length);
564 return false;
565 } else {
566 return ConKickOrBan(argv[1], true, argv[2]);
570 DEF_CONSOLE_CMD(ConUnBan)
572 if (argc == 0) {
573 IConsolePrint(CC_HELP, "Unban a client from a network game. Usage: 'unban <ip | banlist-index>'.");
574 IConsolePrint(CC_HELP, "For a list of banned IP's, see the command 'banlist'.");
575 return true;
578 if (argc != 2) return false;
580 /* Try by IP. */
581 uint index;
582 for (index = 0; index < _network_ban_list.size(); index++) {
583 if (_network_ban_list[index] == argv[1]) break;
586 /* Try by index. */
587 if (index >= _network_ban_list.size()) {
588 index = atoi(argv[1]) - 1U; // let it wrap
591 if (index < _network_ban_list.size()) {
592 IConsolePrint(CC_DEFAULT, "Unbanned {}.", _network_ban_list[index]);
593 _network_ban_list.erase(_network_ban_list.begin() + index);
594 } else {
595 IConsolePrint(CC_DEFAULT, "Invalid list index or IP not in ban-list.");
596 IConsolePrint(CC_DEFAULT, "For a list of banned IP's, see the command 'banlist'.");
599 return true;
602 DEF_CONSOLE_CMD(ConBanList)
604 if (argc == 0) {
605 IConsolePrint(CC_HELP, "List the IP's of banned clients: Usage 'banlist'.");
606 return true;
609 IConsolePrint(CC_DEFAULT, "Banlist:");
611 uint i = 1;
612 for (const auto &entry : _network_ban_list) {
613 IConsolePrint(CC_DEFAULT, " {}) {}", i, entry);
614 i++;
617 return true;
620 DEF_CONSOLE_CMD(ConPauseGame)
622 if (argc == 0) {
623 IConsolePrint(CC_HELP, "Pause a network game. Usage: 'pause'.");
624 return true;
627 if (_game_mode == GM_MENU) {
628 IConsolePrint(CC_ERROR, "This command is only available in-game and in the editor.");
629 return true;
632 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
633 DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
634 if (!_networking) IConsolePrint(CC_DEFAULT, "Game paused.");
635 } else {
636 IConsolePrint(CC_DEFAULT, "Game is already paused.");
639 return true;
642 DEF_CONSOLE_CMD(ConUnpauseGame)
644 if (argc == 0) {
645 IConsolePrint(CC_HELP, "Unpause a network game. Usage: 'unpause'.");
646 return true;
649 if (_game_mode == GM_MENU) {
650 IConsolePrint(CC_ERROR, "This command is only available in-game and in the editor.");
651 return true;
654 if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) {
655 DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
656 if (!_networking) IConsolePrint(CC_DEFAULT, "Game unpaused.");
657 } else if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED) {
658 IConsolePrint(CC_DEFAULT, "Game is in error state and cannot be unpaused via console.");
659 } else if (_pause_mode != PM_UNPAUSED) {
660 IConsolePrint(CC_DEFAULT, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
661 } else {
662 IConsolePrint(CC_DEFAULT, "Game is already unpaused.");
665 return true;
668 DEF_CONSOLE_CMD(ConRcon)
670 if (argc == 0) {
671 IConsolePrint(CC_HELP, "Remote control the server from another client. Usage: 'rcon <password> <command>'.");
672 IConsolePrint(CC_HELP, "Remember to enclose the command in quotes, otherwise only the first parameter is sent.");
673 return true;
676 if (argc < 3) return false;
678 if (_network_server) {
679 IConsoleCmdExec(argv[2]);
680 } else {
681 NetworkClientSendRcon(argv[1], argv[2]);
683 return true;
686 DEF_CONSOLE_CMD(ConStatus)
688 if (argc == 0) {
689 IConsolePrint(CC_HELP, "List the status of all clients connected to the server. Usage 'status'.");
690 return true;
693 NetworkServerShowStatusToConsole();
694 return true;
697 DEF_CONSOLE_CMD(ConServerInfo)
699 if (argc == 0) {
700 IConsolePrint(CC_HELP, "List current and maximum client/company limits. Usage 'server_info'.");
701 IConsolePrint(CC_HELP, "You can change these values by modifying settings 'network.max_clients' and 'network.max_companies'.");
702 return true;
705 IConsolePrint(CC_DEFAULT, "Invite code: {}", _network_server_invite_code);
706 IConsolePrint(CC_DEFAULT, "Current/maximum clients: {:3d}/{:3d}", _network_game_info.clients_on, _settings_client.network.max_clients);
707 IConsolePrint(CC_DEFAULT, "Current/maximum companies: {:3d}/{:3d}", Company::GetNumItems(), _settings_client.network.max_companies);
708 IConsolePrint(CC_DEFAULT, "Current spectators: {:3d}", NetworkSpectatorCount());
710 return true;
713 DEF_CONSOLE_CMD(ConClientNickChange)
715 if (argc != 3) {
716 IConsolePrint(CC_HELP, "Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'.");
717 IConsolePrint(CC_HELP, "For client-id's, see the command 'clients'.");
718 return true;
721 ClientID client_id = (ClientID)atoi(argv[1]);
723 if (client_id == CLIENT_ID_SERVER) {
724 IConsolePrint(CC_ERROR, "Please use the command 'name' to change your own name!");
725 return true;
728 if (NetworkClientInfo::GetByClientID(client_id) == nullptr) {
729 IConsolePrint(CC_ERROR, "Invalid client ID.");
730 return true;
733 std::string client_name(argv[2]);
734 StrTrimInPlace(client_name);
735 if (!NetworkIsValidClientName(client_name)) {
736 IConsolePrint(CC_ERROR, "Cannot give a client an empty name.");
737 return true;
740 if (!NetworkServerChangeClientName(client_id, client_name)) {
741 IConsolePrint(CC_ERROR, "Cannot give a client a duplicate name.");
744 return true;
747 DEF_CONSOLE_CMD(ConJoinCompany)
749 if (argc < 2) {
750 IConsolePrint(CC_HELP, "Request joining another company. Usage: 'join <company-id> [<password>]'.");
751 IConsolePrint(CC_HELP, "For valid company-id see company list, use 255 for spectator.");
752 return true;
755 CompanyID company_id = (CompanyID)(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1]));
757 /* Check we have a valid company id! */
758 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
759 IConsolePrint(CC_ERROR, "Company does not exist. Company-id must be between 1 and {}.", MAX_COMPANIES);
760 return true;
763 if (NetworkClientInfo::GetByClientID(_network_own_client_id)->client_playas == company_id) {
764 IConsolePrint(CC_ERROR, "You are already there!");
765 return true;
768 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
769 IConsolePrint(CC_ERROR, "Cannot join AI company.");
770 return true;
773 /* Check if the company requires a password */
774 if (NetworkCompanyIsPassworded(company_id) && argc < 3) {
775 IConsolePrint(CC_ERROR, "Company {} requires a password to join.", company_id + 1);
776 return true;
779 /* non-dedicated server may just do the move! */
780 if (_network_server) {
781 NetworkServerDoMove(CLIENT_ID_SERVER, company_id);
782 } else {
783 NetworkClientRequestMove(company_id, NetworkCompanyIsPassworded(company_id) ? argv[2] : "");
786 return true;
789 DEF_CONSOLE_CMD(ConMoveClient)
791 if (argc < 3) {
792 IConsolePrint(CC_HELP, "Move a client to another company. Usage: 'move <client-id> <company-id>'.");
793 IConsolePrint(CC_HELP, "For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators.");
794 return true;
797 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID((ClientID)atoi(argv[1]));
798 CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2]));
800 /* check the client exists */
801 if (ci == nullptr) {
802 IConsolePrint(CC_ERROR, "Invalid client-id, check the command 'clients' for valid client-id's.");
803 return true;
806 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
807 IConsolePrint(CC_ERROR, "Company does not exist. Company-id must be between 1 and {}.", MAX_COMPANIES);
808 return true;
811 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
812 IConsolePrint(CC_ERROR, "You cannot move clients to AI companies.");
813 return true;
816 if (ci->client_id == CLIENT_ID_SERVER && _network_dedicated) {
817 IConsolePrint(CC_ERROR, "You cannot move the server!");
818 return true;
821 if (ci->client_playas == company_id) {
822 IConsolePrint(CC_ERROR, "You cannot move someone to where they already are!");
823 return true;
826 /* we are the server, so force the update */
827 NetworkServerDoMove(ci->client_id, company_id);
829 return true;
832 DEF_CONSOLE_CMD(ConResetCompany)
834 if (argc == 0) {
835 IConsolePrint(CC_HELP, "Remove an idle company from the game. Usage: 'reset_company <company-id>'.");
836 IConsolePrint(CC_HELP, "For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
837 return true;
840 if (argc != 2) return false;
842 CompanyID index = (CompanyID)(atoi(argv[1]) - 1);
844 /* Check valid range */
845 if (!Company::IsValidID(index)) {
846 IConsolePrint(CC_ERROR, "Company does not exist. Company-id must be between 1 and {}.", MAX_COMPANIES);
847 return true;
850 if (!Company::IsHumanID(index)) {
851 IConsolePrint(CC_ERROR, "Company is owned by an AI.");
852 return true;
855 if (NetworkCompanyHasClients(index)) {
856 IConsolePrint(CC_ERROR, "Cannot remove company: a client is connected to that company.");
857 return false;
859 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
860 if (ci->client_playas == index) {
861 IConsolePrint(CC_ERROR, "Cannot remove company: the server is connected to that company.");
862 return true;
865 /* It is safe to remove this company */
866 DoCommandP(0, CCA_DELETE | index << 16 | CRR_MANUAL << 24, 0, CMD_COMPANY_CTRL);
867 IConsolePrint(CC_DEFAULT, "Company deleted.");
869 return true;
872 DEF_CONSOLE_CMD(ConNetworkClients)
874 if (argc == 0) {
875 IConsolePrint(CC_HELP, "Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'.");
876 return true;
879 NetworkPrintClients();
881 return true;
884 DEF_CONSOLE_CMD(ConNetworkReconnect)
886 if (argc == 0) {
887 IConsolePrint(CC_HELP, "Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'.");
888 IConsolePrint(CC_HELP, "Company 255 is spectator (default, if not specified), 0 means creating new company.");
889 IConsolePrint(CC_HELP, "All others are a certain company with Company 1 being #1.");
890 return true;
893 CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR;
894 switch (playas) {
895 case 0: playas = COMPANY_NEW_COMPANY; break;
896 case COMPANY_SPECTATOR: /* nothing to do */ break;
897 default:
898 /* From a user pov 0 is a new company, internally it's different and all
899 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
900 if (playas < COMPANY_FIRST + 1 || playas > MAX_COMPANIES + 1) return false;
901 break;
904 if (_settings_client.network.last_joined.empty()) {
905 IConsolePrint(CC_DEFAULT, "No server for reconnecting.");
906 return true;
909 /* Don't resolve the address first, just print it directly as it comes from the config file. */
910 IConsolePrint(CC_DEFAULT, "Reconnecting to {} ...", _settings_client.network.last_joined);
912 return NetworkClientConnectGame(_settings_client.network.last_joined, playas);
915 DEF_CONSOLE_CMD(ConNetworkConnect)
917 if (argc == 0) {
918 IConsolePrint(CC_HELP, "Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'.");
919 IConsolePrint(CC_HELP, "IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'.");
920 IConsolePrint(CC_HELP, "Company #255 is spectator all others are a certain company with Company 1 being #1.");
921 return true;
924 if (argc < 2) return false;
926 return NetworkClientConnectGame(argv[1], COMPANY_NEW_COMPANY);
929 /*********************************
930 * script file console commands
931 *********************************/
933 DEF_CONSOLE_CMD(ConExec)
935 if (argc == 0) {
936 IConsolePrint(CC_HELP, "Execute a local script file. Usage: 'exec <script> <?>'.");
937 return true;
940 if (argc < 2) return false;
942 FILE *script_file = FioFOpenFile(argv[1], "r", BASE_DIR);
944 if (script_file == nullptr) {
945 if (argc == 2 || atoi(argv[2]) != 0) IConsolePrint(CC_ERROR, "Script file '{}' not found.", argv[1]);
946 return true;
949 if (_script_current_depth == 11) {
950 FioFCloseFile(script_file);
951 IConsolePrint(CC_ERROR, "Maximum 'exec' depth reached; script A is calling script B is calling script C ... more than 10 times.");
952 return true;
955 _script_current_depth++;
956 uint script_depth = _script_current_depth;
958 char cmdline[ICON_CMDLN_SIZE];
959 while (fgets(cmdline, sizeof(cmdline), script_file) != nullptr) {
960 /* Remove newline characters from the executing script */
961 for (char *cmdptr = cmdline; *cmdptr != '\0'; cmdptr++) {
962 if (*cmdptr == '\n' || *cmdptr == '\r') {
963 *cmdptr = '\0';
964 break;
967 IConsoleCmdExec(cmdline);
968 /* Ensure that we are still on the same depth or that we returned via 'return'. */
969 assert(_script_current_depth == script_depth || _script_current_depth == script_depth - 1);
971 /* The 'return' command was executed. */
972 if (_script_current_depth == script_depth - 1) break;
975 if (ferror(script_file)) {
976 IConsolePrint(CC_ERROR, "Encountered error while trying to read from script file '{}'.", argv[1]);
979 if (_script_current_depth == script_depth) _script_current_depth--;
980 FioFCloseFile(script_file);
981 return true;
984 DEF_CONSOLE_CMD(ConReturn)
986 if (argc == 0) {
987 IConsolePrint(CC_HELP, "Stop executing a running script. Usage: 'return'.");
988 return true;
991 _script_current_depth--;
992 return true;
995 /*****************************
996 * default console commands
997 ******************************/
998 extern bool CloseConsoleLogIfActive();
1000 DEF_CONSOLE_CMD(ConScript)
1002 extern FILE *_iconsole_output_file;
1004 if (argc == 0) {
1005 IConsolePrint(CC_HELP, "Start or stop logging console output to a file. Usage: 'script <filename>'.");
1006 IConsolePrint(CC_HELP, "If filename is omitted, a running log is stopped if it is active.");
1007 return true;
1010 if (!CloseConsoleLogIfActive()) {
1011 if (argc < 2) return false;
1013 _iconsole_output_file = fopen(argv[1], "ab");
1014 if (_iconsole_output_file == nullptr) {
1015 IConsolePrint(CC_ERROR, "Could not open console log file '{}'.", argv[1]);
1016 } else {
1017 IConsolePrint(CC_INFO, "Console log output started to '{}'.", argv[1]);
1021 return true;
1025 DEF_CONSOLE_CMD(ConEcho)
1027 if (argc == 0) {
1028 IConsolePrint(CC_HELP, "Print back the first argument to the console. Usage: 'echo <arg>'.");
1029 return true;
1032 if (argc < 2) return false;
1033 IConsolePrint(CC_DEFAULT, argv[1]);
1034 return true;
1037 DEF_CONSOLE_CMD(ConEchoC)
1039 if (argc == 0) {
1040 IConsolePrint(CC_HELP, "Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'.");
1041 return true;
1044 if (argc < 3) return false;
1045 IConsolePrint((TextColour)Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1), argv[2]);
1046 return true;
1049 DEF_CONSOLE_CMD(ConNewGame)
1051 if (argc == 0) {
1052 IConsolePrint(CC_HELP, "Start a new game. Usage: 'newgame [seed]'.");
1053 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.");
1054 return true;
1057 StartNewGameWithoutGUI((argc == 2) ? strtoul(argv[1], nullptr, 10) : GENERATE_NEW_SEED);
1058 return true;
1061 DEF_CONSOLE_CMD(ConRestart)
1063 if (argc == 0) {
1064 IConsolePrint(CC_HELP, "Restart game. Usage: 'restart'.");
1065 IConsolePrint(CC_HELP, "Restarts a game. It tries to reproduce the exact same map as the game started with.");
1066 IConsolePrint(CC_HELP, "However:");
1067 IConsolePrint(CC_HELP, " * restarting games started in another version might create another map due to difference in map generation.");
1068 IConsolePrint(CC_HELP, " * restarting games based on scenarios, loaded games or heightmaps will start a new game based on the settings stored in the scenario/savegame.");
1069 return true;
1072 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1073 _settings_game.game_creation.map_x = MapLogX();
1074 _settings_game.game_creation.map_y = FindFirstBit(MapSizeY());
1075 _switch_mode = SM_RESTARTGAME;
1076 return true;
1079 DEF_CONSOLE_CMD(ConReload)
1081 if (argc == 0) {
1082 IConsolePrint(CC_HELP, "Reload game. Usage: 'reload'.");
1083 IConsolePrint(CC_HELP, "Reloads a game.");
1084 IConsolePrint(CC_HELP, " * if you started from a savegame / scenario / heightmap, that exact same savegame / scenario / heightmap will be loaded.");
1085 IConsolePrint(CC_HELP, " * if you started from a new game, this acts the same as 'restart'.");
1086 return true;
1089 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1090 _settings_game.game_creation.map_x = MapLogX();
1091 _settings_game.game_creation.map_y = FindFirstBit(MapSizeY());
1092 _switch_mode = SM_RELOADGAME;
1093 return true;
1097 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1098 * @param buf The buffer to print.
1099 * @note All newlines are replace by '\0' characters.
1101 static void PrintLineByLine(char *buf)
1103 char *p = buf;
1104 /* Print output line by line */
1105 for (char *p2 = buf; *p2 != '\0'; p2++) {
1106 if (*p2 == '\n') {
1107 *p2 = '\0';
1108 IConsolePrint(CC_DEFAULT, p);
1109 p = p2 + 1;
1114 DEF_CONSOLE_CMD(ConListAILibs)
1116 char buf[4096];
1117 AI::GetConsoleLibraryList(buf, lastof(buf));
1119 PrintLineByLine(buf);
1121 return true;
1124 DEF_CONSOLE_CMD(ConListAI)
1126 char buf[4096];
1127 AI::GetConsoleList(buf, lastof(buf));
1129 PrintLineByLine(buf);
1131 return true;
1134 DEF_CONSOLE_CMD(ConListGameLibs)
1136 char buf[4096];
1137 Game::GetConsoleLibraryList(buf, lastof(buf));
1139 PrintLineByLine(buf);
1141 return true;
1144 DEF_CONSOLE_CMD(ConListGame)
1146 char buf[4096];
1147 Game::GetConsoleList(buf, lastof(buf));
1149 PrintLineByLine(buf);
1151 return true;
1154 DEF_CONSOLE_CMD(ConStartAI)
1156 if (argc == 0 || argc > 3) {
1157 IConsolePrint(CC_HELP, "Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'.");
1158 IConsolePrint(CC_HELP, "Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1159 IConsolePrint(CC_HELP, "If <settings> is given, it is parsed and the AI settings are set to that.");
1160 return true;
1163 if (_game_mode != GM_NORMAL) {
1164 IConsolePrint(CC_ERROR, "AIs can only be managed in a game.");
1165 return true;
1168 if (Company::GetNumItems() == CompanyPool::MAX_SIZE) {
1169 IConsolePrint(CC_ERROR, "Can't start a new AI (no more free slots).");
1170 return true;
1172 if (_networking && !_network_server) {
1173 IConsolePrint(CC_ERROR, "Only the server can start a new AI.");
1174 return true;
1176 if (_networking && !_settings_game.ai.ai_in_multiplayer) {
1177 IConsolePrint(CC_ERROR, "AIs are not allowed in multiplayer by configuration.");
1178 IConsolePrint(CC_ERROR, "Switch AI -> AI in multiplayer to True.");
1179 return true;
1181 if (!AI::CanStartNew()) {
1182 IConsolePrint(CC_ERROR, "Can't start a new AI.");
1183 return true;
1186 int n = 0;
1187 /* Find the next free slot */
1188 for (const Company *c : Company::Iterate()) {
1189 if (c->index != n) break;
1190 n++;
1193 AIConfig *config = AIConfig::GetConfig((CompanyID)n);
1194 if (argc >= 2) {
1195 config->Change(argv[1], -1, false);
1197 /* If the name is not found, and there is a dot in the name,
1198 * try again with the assumption everything right of the dot is
1199 * the version the user wants to load. */
1200 if (!config->HasScript()) {
1201 char *name = stredup(argv[1]);
1202 char *e = strrchr(name, '.');
1203 if (e != nullptr) {
1204 *e = '\0';
1205 e++;
1207 int version = atoi(e);
1208 config->Change(name, version, true);
1210 free(name);
1213 if (!config->HasScript()) {
1214 IConsolePrint(CC_ERROR, "Failed to load the specified AI.");
1215 return true;
1217 if (argc == 3) {
1218 config->StringToSettings(argv[2]);
1222 /* Start a new AI company */
1223 DoCommandP(0, CCA_NEW_AI | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
1225 return true;
1228 DEF_CONSOLE_CMD(ConReloadAI)
1230 if (argc != 2) {
1231 IConsolePrint(CC_HELP, "Reload an AI. Usage: 'reload_ai <company-id>'.");
1232 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.");
1233 return true;
1236 if (_game_mode != GM_NORMAL) {
1237 IConsolePrint(CC_ERROR, "AIs can only be managed in a game.");
1238 return true;
1241 if (_networking && !_network_server) {
1242 IConsolePrint(CC_ERROR, "Only the server can reload an AI.");
1243 return true;
1246 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1247 if (!Company::IsValidID(company_id)) {
1248 IConsolePrint(CC_ERROR, "Unknown company. Company range is between 1 and {}.", MAX_COMPANIES);
1249 return true;
1252 /* In singleplayer mode the player can be in an AI company, after cheating or loading network save with an AI in first slot. */
1253 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1254 IConsolePrint(CC_ERROR, "Company is not controlled by an AI.");
1255 return true;
1258 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1259 DoCommandP(0, CCA_DELETE | company_id << 16 | CRR_MANUAL << 24, 0, CMD_COMPANY_CTRL);
1260 DoCommandP(0, CCA_NEW_AI | company_id << 16, 0, CMD_COMPANY_CTRL);
1261 IConsolePrint(CC_DEFAULT, "AI reloaded.");
1263 return true;
1266 DEF_CONSOLE_CMD(ConStopAI)
1268 if (argc != 2) {
1269 IConsolePrint(CC_HELP, "Stop an AI. Usage: 'stop_ai <company-id>'.");
1270 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.");
1271 return true;
1274 if (_game_mode != GM_NORMAL) {
1275 IConsolePrint(CC_ERROR, "AIs can only be managed in a game.");
1276 return true;
1279 if (_networking && !_network_server) {
1280 IConsolePrint(CC_ERROR, "Only the server can stop an AI.");
1281 return true;
1284 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1285 if (!Company::IsValidID(company_id)) {
1286 IConsolePrint(CC_ERROR, "Unknown company. Company range is between 1 and {}.", MAX_COMPANIES);
1287 return true;
1290 /* In singleplayer mode the player can be in an AI company, after cheating or loading network save with an AI in first slot. */
1291 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1292 IConsolePrint(CC_ERROR, "Company is not controlled by an AI.");
1293 return true;
1296 /* Now kill the company of the AI. */
1297 DoCommandP(0, CCA_DELETE | company_id << 16 | CRR_MANUAL << 24, 0, CMD_COMPANY_CTRL);
1298 IConsolePrint(CC_DEFAULT, "AI stopped, company deleted.");
1300 return true;
1303 DEF_CONSOLE_CMD(ConRescanAI)
1305 if (argc == 0) {
1306 IConsolePrint(CC_HELP, "Rescan the AI dir for scripts. Usage: 'rescan_ai'.");
1307 return true;
1310 if (_networking && !_network_server) {
1311 IConsolePrint(CC_ERROR, "Only the server can rescan the AI dir for scripts.");
1312 return true;
1315 AI::Rescan();
1317 return true;
1320 DEF_CONSOLE_CMD(ConRescanGame)
1322 if (argc == 0) {
1323 IConsolePrint(CC_HELP, "Rescan the Game Script dir for scripts. Usage: 'rescan_game'.");
1324 return true;
1327 if (_networking && !_network_server) {
1328 IConsolePrint(CC_ERROR, "Only the server can rescan the Game Script dir for scripts.");
1329 return true;
1332 Game::Rescan();
1334 return true;
1337 DEF_CONSOLE_CMD(ConRescanNewGRF)
1339 if (argc == 0) {
1340 IConsolePrint(CC_HELP, "Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'.");
1341 return true;
1344 if (!RequestNewGRFScan()) {
1345 IConsolePrint(CC_ERROR, "NewGRF scanning is already running. Please wait until completed to run again.");
1348 return true;
1351 DEF_CONSOLE_CMD(ConGetSeed)
1353 if (argc == 0) {
1354 IConsolePrint(CC_HELP, "Returns the seed used to create this game. Usage: 'getseed'.");
1355 IConsolePrint(CC_HELP, "The seed can be used to reproduce the exact same map as the game started with.");
1356 return true;
1359 IConsolePrint(CC_DEFAULT, "Generation Seed: {}", _settings_game.game_creation.generation_seed);
1360 return true;
1363 DEF_CONSOLE_CMD(ConGetDate)
1365 if (argc == 0) {
1366 IConsolePrint(CC_HELP, "Returns the current date (year-month-day) of the game. Usage: 'getdate'.");
1367 return true;
1370 YearMonthDay ymd;
1371 ConvertDateToYMD(_date, &ymd);
1372 IConsolePrint(CC_DEFAULT, "Date: {:04d}-{:02d}-{:02d}", ymd.year, ymd.month + 1, ymd.day);
1373 return true;
1376 DEF_CONSOLE_CMD(ConGetSysDate)
1378 if (argc == 0) {
1379 IConsolePrint(CC_HELP, "Returns the current date (year-month-day) of your system. Usage: 'getsysdate'.");
1380 return true;
1383 char buffer[lengthof("2000-01-02 03:04:05")];
1384 LocalTime::Format(buffer, lastof(buffer), "%Y-%m-%d %H:%M:%S");
1385 IConsolePrint(CC_DEFAULT, "System Date: {}", buffer);
1386 return true;
1390 DEF_CONSOLE_CMD(ConAlias)
1392 IConsoleAlias *alias;
1394 if (argc == 0) {
1395 IConsolePrint(CC_HELP, "Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'.");
1396 return true;
1399 if (argc < 3) return false;
1401 alias = IConsole::AliasGet(argv[1]);
1402 if (alias == nullptr) {
1403 IConsole::AliasRegister(argv[1], argv[2]);
1404 } else {
1405 alias->cmdline = argv[2];
1407 return true;
1410 DEF_CONSOLE_CMD(ConScreenShot)
1412 if (argc == 0) {
1413 IConsolePrint(CC_HELP, "Create a screenshot of the game. Usage: 'screenshot [viewport | normal | big | giant | heightmap | minimap] [no_con] [size <width> <height>] [<filename>]'.");
1414 IConsolePrint(CC_HELP, " 'viewport' (default) makes a screenshot of the current viewport (including menus, windows).");
1415 IConsolePrint(CC_HELP, " 'normal' makes a screenshot of the visible area.");
1416 IConsolePrint(CC_HELP, " 'big' makes a zoomed-in screenshot of the visible area.");
1417 IConsolePrint(CC_HELP, " 'giant' makes a screenshot of the whole map.");
1418 IConsolePrint(CC_HELP, " 'heightmap' makes a heightmap screenshot of the map that can be loaded in as heightmap.");
1419 IConsolePrint(CC_HELP, " 'minimap' makes a top-viewed minimap screenshot of the whole world which represents one tile by one pixel.");
1420 IConsolePrint(CC_HELP, " 'no_con' hides the console to create the screenshot (only useful in combination with 'viewport').");
1421 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').");
1422 return true;
1425 if (argc > 7) return false;
1427 ScreenshotType type = SC_VIEWPORT;
1428 uint32 width = 0;
1429 uint32 height = 0;
1430 std::string name{};
1431 uint32 arg_index = 1;
1433 if (argc > arg_index) {
1434 if (strcmp(argv[arg_index], "viewport") == 0) {
1435 type = SC_VIEWPORT;
1436 arg_index += 1;
1437 } else if (strcmp(argv[arg_index], "normal") == 0) {
1438 type = SC_DEFAULTZOOM;
1439 arg_index += 1;
1440 } else if (strcmp(argv[arg_index], "big") == 0) {
1441 type = SC_ZOOMEDIN;
1442 arg_index += 1;
1443 } else if (strcmp(argv[arg_index], "giant") == 0) {
1444 type = SC_WORLD;
1445 arg_index += 1;
1446 } else if (strcmp(argv[arg_index], "heightmap") == 0) {
1447 type = SC_HEIGHTMAP;
1448 arg_index += 1;
1449 } else if (strcmp(argv[arg_index], "minimap") == 0) {
1450 type = SC_MINIMAP;
1451 arg_index += 1;
1455 if (argc > arg_index && strcmp(argv[arg_index], "no_con") == 0) {
1456 if (type != SC_VIEWPORT) {
1457 IConsolePrint(CC_ERROR, "'no_con' can only be used in combination with 'viewport'.");
1458 return true;
1460 IConsoleClose();
1461 arg_index += 1;
1464 if (argc > arg_index + 2 && strcmp(argv[arg_index], "size") == 0) {
1465 /* size <width> <height> */
1466 if (type != SC_DEFAULTZOOM && type != SC_ZOOMEDIN) {
1467 IConsolePrint(CC_ERROR, "'size' can only be used in combination with 'normal' or 'big'.");
1468 return true;
1470 GetArgumentInteger(&width, argv[arg_index + 1]);
1471 GetArgumentInteger(&height, argv[arg_index + 2]);
1472 arg_index += 3;
1475 if (argc > arg_index) {
1476 /* Last parameter that was not one of the keywords must be the filename. */
1477 name = argv[arg_index];
1478 arg_index += 1;
1481 if (argc > arg_index) {
1482 /* We have parameters we did not process; means we misunderstood any of the above. */
1483 return false;
1486 MakeScreenshot(type, name, width, height);
1487 return true;
1490 DEF_CONSOLE_CMD(ConInfoCmd)
1492 if (argc == 0) {
1493 IConsolePrint(CC_HELP, "Print out debugging information about a command. Usage: 'info_cmd <cmd>'.");
1494 return true;
1497 if (argc < 2) return false;
1499 const IConsoleCmd *cmd = IConsole::CmdGet(argv[1]);
1500 if (cmd == nullptr) {
1501 IConsolePrint(CC_ERROR, "The given command was not found.");
1502 return true;
1505 IConsolePrint(CC_DEFAULT, "Command name: '{}'", cmd->name);
1507 if (cmd->hook != nullptr) IConsolePrint(CC_DEFAULT, "Command is hooked.");
1509 return true;
1512 DEF_CONSOLE_CMD(ConDebugLevel)
1514 if (argc == 0) {
1515 IConsolePrint(CC_HELP, "Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'.");
1516 IConsolePrint(CC_HELP, "Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'\"s.");
1517 return true;
1520 if (argc > 2) return false;
1522 if (argc == 1) {
1523 IConsolePrint(CC_DEFAULT, "Current debug-level: '{}'", GetDebugString());
1524 } else {
1525 SetDebugString(argv[1]);
1528 return true;
1531 DEF_CONSOLE_CMD(ConExit)
1533 if (argc == 0) {
1534 IConsolePrint(CC_HELP, "Exit the game. Usage: 'exit'.");
1535 return true;
1538 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
1540 _exit_game = true;
1541 return true;
1544 DEF_CONSOLE_CMD(ConPart)
1546 if (argc == 0) {
1547 IConsolePrint(CC_HELP, "Leave the currently joined/running game (only ingame). Usage: 'part'.");
1548 return true;
1551 if (_game_mode != GM_NORMAL) return false;
1553 _switch_mode = SM_MENU;
1554 return true;
1557 DEF_CONSOLE_CMD(ConHelp)
1559 if (argc == 2) {
1560 const IConsoleCmd *cmd;
1561 const IConsoleAlias *alias;
1563 cmd = IConsole::CmdGet(argv[1]);
1564 if (cmd != nullptr) {
1565 cmd->proc(0, nullptr);
1566 return true;
1569 alias = IConsole::AliasGet(argv[1]);
1570 if (alias != nullptr) {
1571 cmd = IConsole::CmdGet(alias->cmdline);
1572 if (cmd != nullptr) {
1573 cmd->proc(0, nullptr);
1574 return true;
1576 IConsolePrint(CC_ERROR, "Alias is of special type, please see its execution-line: '{}'.", alias->cmdline);
1577 return true;
1580 IConsolePrint(CC_ERROR, "Command not found.");
1581 return true;
1584 IConsolePrint(TC_LIGHT_BLUE, " ---- OpenTTD Console Help ---- ");
1585 IConsolePrint(CC_DEFAULT, " - commands: the command to list all commands is 'list_cmds'.");
1586 IConsolePrint(CC_DEFAULT, " call commands with '<command> <arg2> <arg3>...'");
1587 IConsolePrint(CC_DEFAULT, " - to assign strings, or use them as arguments, enclose it within quotes.");
1588 IConsolePrint(CC_DEFAULT, " like this: '<command> \"string argument with spaces\"'.");
1589 IConsolePrint(CC_DEFAULT, " - use 'help <command>' to get specific information.");
1590 IConsolePrint(CC_DEFAULT, " - scroll console output with shift + (up | down | pageup | pagedown).");
1591 IConsolePrint(CC_DEFAULT, " - scroll console input history with the up or down arrows.");
1592 IConsolePrint(CC_DEFAULT, "");
1593 return true;
1596 DEF_CONSOLE_CMD(ConListCommands)
1598 if (argc == 0) {
1599 IConsolePrint(CC_HELP, "List all registered commands. Usage: 'list_cmds [<pre-filter>]'.");
1600 return true;
1603 for (auto &it : IConsole::Commands()) {
1604 const IConsoleCmd *cmd = &it.second;
1605 if (argv[1] == nullptr || cmd->name.find(argv[1]) != std::string::npos) {
1606 if (cmd->hook == nullptr || cmd->hook(false) != CHR_HIDE) IConsolePrint(CC_DEFAULT, cmd->name);
1610 return true;
1613 DEF_CONSOLE_CMD(ConListAliases)
1615 if (argc == 0) {
1616 IConsolePrint(CC_HELP, "List all registered aliases. Usage: 'list_aliases [<pre-filter>]'.");
1617 return true;
1620 for (auto &it : IConsole::Aliases()) {
1621 const IConsoleAlias *alias = &it.second;
1622 if (argv[1] == nullptr || alias->name.find(argv[1]) != std::string::npos) {
1623 IConsolePrint(CC_DEFAULT, "{} => {}", alias->name, alias->cmdline);
1627 return true;
1630 DEF_CONSOLE_CMD(ConCompanies)
1632 if (argc == 0) {
1633 IConsolePrint(CC_HELP, "List the details of all companies in the game. Usage 'companies'.");
1634 return true;
1637 for (const Company *c : Company::Iterate()) {
1638 /* Grab the company name */
1639 char company_name[512];
1640 SetDParam(0, c->index);
1641 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1643 const char *password_state = "";
1644 if (c->is_ai) {
1645 password_state = "AI";
1646 } else if (_network_server) {
1647 password_state = _network_company_states[c->index].password.empty() ? "unprotected" : "protected";
1650 char colour[512];
1651 GetString(colour, STR_COLOUR_DARK_BLUE + _company_colours[c->index], lastof(colour));
1652 IConsolePrint(CC_INFO, "#:{}({}) Company Name: '{}' Year Founded: {} Money: {} Loan: {} Value: {} (T:{}, R:{}, P:{}, S:{}) {}",
1653 c->index + 1, colour, company_name,
1654 c->inaugurated_year, (int64)c->money, (int64)c->current_loan, (int64)CalculateCompanyValue(c),
1655 c->group_all[VEH_TRAIN].num_vehicle,
1656 c->group_all[VEH_ROAD].num_vehicle,
1657 c->group_all[VEH_AIRCRAFT].num_vehicle,
1658 c->group_all[VEH_SHIP].num_vehicle,
1659 password_state);
1662 return true;
1665 DEF_CONSOLE_CMD(ConSay)
1667 if (argc == 0) {
1668 IConsolePrint(CC_HELP, "Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'.");
1669 return true;
1672 if (argc != 2) return false;
1674 if (!_network_server) {
1675 NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
1676 } else {
1677 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1678 NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin);
1681 return true;
1684 DEF_CONSOLE_CMD(ConSayCompany)
1686 if (argc == 0) {
1687 IConsolePrint(CC_HELP, "Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'.");
1688 IConsolePrint(CC_HELP, "CompanyNo is the company that plays as company <companyno>, 1 through max_companies.");
1689 return true;
1692 if (argc != 3) return false;
1694 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1695 if (!Company::IsValidID(company_id)) {
1696 IConsolePrint(CC_DEFAULT, "Unknown company. Company range is between 1 and {}.", MAX_COMPANIES);
1697 return true;
1700 if (!_network_server) {
1701 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]);
1702 } else {
1703 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1704 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2], CLIENT_ID_SERVER, from_admin);
1707 return true;
1710 DEF_CONSOLE_CMD(ConSayClient)
1712 if (argc == 0) {
1713 IConsolePrint(CC_HELP, "Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'.");
1714 IConsolePrint(CC_HELP, "For client-id's, see the command 'clients'.");
1715 return true;
1718 if (argc != 3) return false;
1720 if (!_network_server) {
1721 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
1722 } else {
1723 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1724 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin);
1727 return true;
1730 DEF_CONSOLE_CMD(ConCompanyPassword)
1732 if (argc == 0) {
1733 if (_network_dedicated) {
1734 IConsolePrint(CC_HELP, "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\".");
1735 } else if (_network_server) {
1736 IConsolePrint(CC_HELP, "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'.");
1737 } else {
1738 IConsolePrint(CC_HELP, "Change the password of your company. Usage: 'company_pw \"<password>\"'.");
1741 IConsolePrint(CC_HELP, "Use \"*\" to disable the password.");
1742 return true;
1745 CompanyID company_id;
1746 std::string password;
1747 const char *errormsg;
1749 if (argc == 2) {
1750 company_id = _local_company;
1751 password = argv[1];
1752 errormsg = "You have to own a company to make use of this command.";
1753 } else if (argc == 3 && _network_server) {
1754 company_id = (CompanyID)(atoi(argv[1]) - 1);
1755 password = argv[2];
1756 errormsg = "You have to specify the ID of a valid human controlled company.";
1757 } else {
1758 return false;
1761 if (!Company::IsValidHumanID(company_id)) {
1762 IConsolePrint(CC_ERROR, errormsg);
1763 return false;
1766 password = NetworkChangeCompanyPassword(company_id, password);
1768 if (password.empty()) {
1769 IConsolePrint(CC_INFO, "Company password cleared.");
1770 } else {
1771 IConsolePrint(CC_INFO, "Company password changed to '{}'.", password);
1774 return true;
1777 /* Content downloading only is available with ZLIB */
1778 #if defined(WITH_ZLIB)
1779 #include "network/network_content.h"
1781 /** Resolve a string to a content type. */
1782 static ContentType StringToContentType(const char *str)
1784 static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1785 for (uint i = 1 /* there is no type 0 */; i < lengthof(inv_lookup); i++) {
1786 if (strcasecmp(str, inv_lookup[i]) == 0) return (ContentType)i;
1788 return CONTENT_TYPE_END;
1791 /** Asynchronous callback */
1792 struct ConsoleContentCallback : public ContentCallback {
1793 void OnConnect(bool success)
1795 IConsolePrint(CC_DEFAULT, "Content server connection {}.", success ? "established" : "failed");
1798 void OnDisconnect()
1800 IConsolePrint(CC_DEFAULT, "Content server connection closed.");
1803 void OnDownloadComplete(ContentID cid)
1805 IConsolePrint(CC_DEFAULT, "Completed download of {}.", cid);
1810 * Outputs content state information to console
1811 * @param ci the content info
1813 static void OutputContentState(const ContentInfo *const ci)
1815 static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1816 static_assert(lengthof(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN);
1817 static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1818 static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR };
1820 char buf[sizeof(ci->md5sum) * 2 + 1];
1821 md5sumToString(buf, lastof(buf), ci->md5sum);
1822 IConsolePrint(state_to_colour[ci->state], "{}, {}, {}, {}, {:08X}, {}", ci->id, types[ci->type - 1], states[ci->state], ci->name, ci->unique_id, buf);
1825 DEF_CONSOLE_CMD(ConContent)
1827 static ContentCallback *cb = nullptr;
1828 if (cb == nullptr) {
1829 cb = new ConsoleContentCallback();
1830 _network_content_client.AddCallback(cb);
1833 if (argc <= 1) {
1834 IConsolePrint(CC_HELP, "Query, select and download content. Usage: 'content update|upgrade|select [id]|unselect [all|id]|state [filter]|download'.");
1835 IConsolePrint(CC_HELP, " update: get a new list of downloadable content; must be run first.");
1836 IConsolePrint(CC_HELP, " upgrade: select all items that are upgrades.");
1837 IConsolePrint(CC_HELP, " select: select a specific item given by its id. If no parameter is given, all selected content will be listed.");
1838 IConsolePrint(CC_HELP, " unselect: unselect a specific item given by its id or 'all' to unselect all.");
1839 IConsolePrint(CC_HELP, " state: show the download/select state of all downloadable content. Optionally give a filter string.");
1840 IConsolePrint(CC_HELP, " download: download all content you've selected.");
1841 return true;
1844 if (strcasecmp(argv[1], "update") == 0) {
1845 _network_content_client.RequestContentList((argc > 2) ? StringToContentType(argv[2]) : CONTENT_TYPE_END);
1846 return true;
1849 if (strcasecmp(argv[1], "upgrade") == 0) {
1850 _network_content_client.SelectUpgrade();
1851 return true;
1854 if (strcasecmp(argv[1], "select") == 0) {
1855 if (argc <= 2) {
1856 /* List selected content */
1857 IConsolePrint(CC_WHITE, "id, type, state, name");
1858 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1859 if ((*iter)->state != ContentInfo::SELECTED && (*iter)->state != ContentInfo::AUTOSELECTED) continue;
1860 OutputContentState(*iter);
1862 } else if (strcasecmp(argv[2], "all") == 0) {
1863 /* The intention of this function was that you could download
1864 * everything after a filter was applied; but this never really
1865 * took off. Instead, a select few people used this functionality
1866 * to download every available package on BaNaNaS. This is not in
1867 * the spirit of this service. Additionally, these few people were
1868 * good for 70% of the consumed bandwidth of BaNaNaS. */
1869 IConsolePrint(CC_ERROR, "'select all' is no longer supported since 1.11.");
1870 } else {
1871 _network_content_client.Select((ContentID)atoi(argv[2]));
1873 return true;
1876 if (strcasecmp(argv[1], "unselect") == 0) {
1877 if (argc <= 2) {
1878 IConsolePrint(CC_ERROR, "You must enter the id.");
1879 return false;
1881 if (strcasecmp(argv[2], "all") == 0) {
1882 _network_content_client.UnselectAll();
1883 } else {
1884 _network_content_client.Unselect((ContentID)atoi(argv[2]));
1886 return true;
1889 if (strcasecmp(argv[1], "state") == 0) {
1890 IConsolePrint(CC_WHITE, "id, type, state, name");
1891 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1892 if (argc > 2 && strcasestr((*iter)->name.c_str(), argv[2]) == nullptr) continue;
1893 OutputContentState(*iter);
1895 return true;
1898 if (strcasecmp(argv[1], "download") == 0) {
1899 uint files;
1900 uint bytes;
1901 _network_content_client.DownloadSelectedContent(files, bytes);
1902 IConsolePrint(CC_DEFAULT, "Downloading {} file(s) ({} bytes).", files, bytes);
1903 return true;
1906 return false;
1908 #endif /* defined(WITH_ZLIB) */
1910 DEF_CONSOLE_CMD(ConSetting)
1912 if (argc == 0) {
1913 IConsolePrint(CC_HELP, "Change setting for all clients. Usage: 'setting <name> [<value>]'.");
1914 IConsolePrint(CC_HELP, "Omitting <value> will print out the current value of the setting.");
1915 return true;
1918 if (argc == 1 || argc > 3) return false;
1920 if (argc == 2) {
1921 IConsoleGetSetting(argv[1]);
1922 } else {
1923 IConsoleSetSetting(argv[1], argv[2]);
1926 return true;
1929 DEF_CONSOLE_CMD(ConSettingNewgame)
1931 if (argc == 0) {
1932 IConsolePrint(CC_HELP, "Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'.");
1933 IConsolePrint(CC_HELP, "Omitting <value> will print out the current value of the setting.");
1934 return true;
1937 if (argc == 1 || argc > 3) return false;
1939 if (argc == 2) {
1940 IConsoleGetSetting(argv[1], true);
1941 } else {
1942 IConsoleSetSetting(argv[1], argv[2], true);
1945 return true;
1948 DEF_CONSOLE_CMD(ConListSettings)
1950 if (argc == 0) {
1951 IConsolePrint(CC_HELP, "List settings. Usage: 'list_settings [<pre-filter>]'.");
1952 return true;
1955 if (argc > 2) return false;
1957 IConsoleListSettings((argc == 2) ? argv[1] : nullptr);
1958 return true;
1961 DEF_CONSOLE_CMD(ConGamelogPrint)
1963 GamelogPrintConsole();
1964 return true;
1967 DEF_CONSOLE_CMD(ConNewGRFReload)
1969 if (argc == 0) {
1970 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!");
1971 return true;
1974 ReloadNewGRFData();
1975 return true;
1978 DEF_CONSOLE_CMD(ConNewGRFProfile)
1980 if (argc == 0) {
1981 IConsolePrint(CC_HELP, "Collect performance data about NewGRF sprite requests and callbacks. Sub-commands can be abbreviated.");
1982 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile [list]':");
1983 IConsolePrint(CC_HELP, " List all NewGRFs that can be profiled, and their status.");
1984 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile select <grf-num>...':");
1985 IConsolePrint(CC_HELP, " Select one or more GRFs for profiling.");
1986 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile unselect <grf-num>...':");
1987 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.");
1988 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile start [<num-days>]':");
1989 IConsolePrint(CC_HELP, " Begin profiling all selected GRFs. If a number of days is provided, profiling stops after that many in-game days.");
1990 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile stop':");
1991 IConsolePrint(CC_HELP, " End profiling and write the collected data to CSV files.");
1992 IConsolePrint(CC_HELP, "Usage: 'newgrf_profile abort':");
1993 IConsolePrint(CC_HELP, " End profiling and discard all collected data.");
1994 return true;
1997 extern const std::vector<GRFFile *> &GetAllGRFFiles();
1998 const std::vector<GRFFile *> &files = GetAllGRFFiles();
2000 /* "list" sub-command */
2001 if (argc == 1 || strncasecmp(argv[1], "lis", 3) == 0) {
2002 IConsolePrint(CC_INFO, "Loaded GRF files:");
2003 int i = 1;
2004 for (GRFFile *grf : files) {
2005 auto profiler = std::find_if(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; });
2006 bool selected = profiler != _newgrf_profilers.end();
2007 bool active = selected && profiler->active;
2008 TextColour tc = active ? TC_LIGHT_BLUE : selected ? TC_GREEN : CC_INFO;
2009 const char *statustext = active ? " (active)" : selected ? " (selected)" : "";
2010 IConsolePrint(tc, "{}: [{:08X}] {}{}", i, BSWAP32(grf->grfid), grf->filename, statustext);
2011 i++;
2013 return true;
2016 /* "select" sub-command */
2017 if (strncasecmp(argv[1], "sel", 3) == 0 && argc >= 3) {
2018 for (size_t argnum = 2; argnum < argc; ++argnum) {
2019 int grfnum = atoi(argv[argnum]);
2020 if (grfnum < 1 || grfnum > (int)files.size()) { // safe cast, files.size() should not be larger than a few hundred in the most extreme cases
2021 IConsolePrint(CC_WARNING, "GRF number {} out of range, not added.", grfnum);
2022 continue;
2024 GRFFile *grf = files[grfnum - 1];
2025 if (std::any_of(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; })) {
2026 IConsolePrint(CC_WARNING, "GRF number {} [{:08X}] is already selected for profiling.", grfnum, BSWAP32(grf->grfid));
2027 continue;
2029 _newgrf_profilers.emplace_back(grf);
2031 return true;
2034 /* "unselect" sub-command */
2035 if (strncasecmp(argv[1], "uns", 3) == 0 && argc >= 3) {
2036 for (size_t argnum = 2; argnum < argc; ++argnum) {
2037 if (strcasecmp(argv[argnum], "all") == 0) {
2038 _newgrf_profilers.clear();
2039 break;
2041 int grfnum = atoi(argv[argnum]);
2042 if (grfnum < 1 || grfnum > (int)files.size()) {
2043 IConsolePrint(CC_WARNING, "GRF number {} out of range, not removing.", grfnum);
2044 continue;
2046 GRFFile *grf = files[grfnum - 1];
2047 auto pos = std::find_if(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; });
2048 if (pos != _newgrf_profilers.end()) _newgrf_profilers.erase(pos);
2050 return true;
2053 /* "start" sub-command */
2054 if (strncasecmp(argv[1], "sta", 3) == 0) {
2055 std::string grfids;
2056 size_t started = 0;
2057 for (NewGRFProfiler &pr : _newgrf_profilers) {
2058 if (!pr.active) {
2059 pr.Start();
2060 started++;
2062 if (!grfids.empty()) grfids += ", ";
2063 char grfidstr[12]{ 0 };
2064 seprintf(grfidstr, lastof(grfidstr), "[%08X]", BSWAP32(pr.grffile->grfid));
2065 grfids += grfidstr;
2068 if (started > 0) {
2069 IConsolePrint(CC_DEBUG, "Started profiling for GRFID{} {}.", (started > 1) ? "s" : "", grfids);
2070 if (argc >= 3) {
2071 int days = std::max(atoi(argv[2]), 1);
2072 _newgrf_profile_end_date = _date + days;
2074 char datestrbuf[32]{ 0 };
2075 SetDParam(0, _newgrf_profile_end_date);
2076 GetString(datestrbuf, STR_JUST_DATE_ISO, lastof(datestrbuf));
2077 IConsolePrint(CC_DEBUG, "Profiling will automatically stop on game date {}.", datestrbuf);
2078 } else {
2079 _newgrf_profile_end_date = MAX_DAY;
2081 } else if (_newgrf_profilers.empty()) {
2082 IConsolePrint(CC_ERROR, "No GRFs selected for profiling, did not start.");
2083 } else {
2084 IConsolePrint(CC_ERROR, "Did not start profiling for any GRFs, all selected GRFs are already profiling.");
2086 return true;
2089 /* "stop" sub-command */
2090 if (strncasecmp(argv[1], "sto", 3) == 0) {
2091 NewGRFProfiler::FinishAll();
2092 return true;
2095 /* "abort" sub-command */
2096 if (strncasecmp(argv[1], "abo", 3) == 0) {
2097 for (NewGRFProfiler &pr : _newgrf_profilers) {
2098 pr.Abort();
2100 _newgrf_profile_end_date = MAX_DAY;
2101 return true;
2104 return false;
2107 #ifdef _DEBUG
2108 /******************
2109 * debug commands
2110 ******************/
2112 static void IConsoleDebugLibRegister()
2114 IConsole::CmdRegister("resettile", ConResetTile);
2115 IConsole::AliasRegister("dbg_echo", "echo %A; echo %B");
2116 IConsole::AliasRegister("dbg_echo2", "echo %!");
2118 #endif
2120 DEF_CONSOLE_CMD(ConFramerate)
2122 extern void ConPrintFramerate(); // framerate_gui.cpp
2124 if (argc == 0) {
2125 IConsolePrint(CC_HELP, "Show frame rate and game speed information.");
2126 return true;
2129 ConPrintFramerate();
2130 return true;
2133 DEF_CONSOLE_CMD(ConFramerateWindow)
2135 extern void ShowFramerateWindow();
2137 if (argc == 0) {
2138 IConsolePrint(CC_HELP, "Open the frame rate window.");
2139 return true;
2142 if (_network_dedicated) {
2143 IConsolePrint(CC_ERROR, "Can not open frame rate window on a dedicated server.");
2144 return false;
2147 ShowFramerateWindow();
2148 return true;
2151 static void ConDumpRoadTypes()
2153 IConsolePrint(CC_DEFAULT, " Flags:");
2154 IConsolePrint(CC_DEFAULT, " c = catenary");
2155 IConsolePrint(CC_DEFAULT, " l = no level crossings");
2156 IConsolePrint(CC_DEFAULT, " X = no houses");
2157 IConsolePrint(CC_DEFAULT, " h = hidden");
2158 IConsolePrint(CC_DEFAULT, " T = buildable by towns");
2160 std::map<uint32, const GRFFile *> grfs;
2161 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
2162 const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
2163 if (rti->label == 0) continue;
2164 uint32 grfid = 0;
2165 const GRFFile *grf = rti->grffile[ROTSG_GROUND];
2166 if (grf != nullptr) {
2167 grfid = grf->grfid;
2168 grfs.emplace(grfid, grf);
2170 IConsolePrint(CC_DEFAULT, " {:02d} {} {:c}{:c}{:c}{:c}, Flags: {}{}{}{}{}, GRF: {:08X}, {}",
2171 (uint)rt,
2172 RoadTypeIsTram(rt) ? "Tram" : "Road",
2173 rti->label >> 24, rti->label >> 16, rti->label >> 8, rti->label,
2174 HasBit(rti->flags, ROTF_CATENARY) ? 'c' : '-',
2175 HasBit(rti->flags, ROTF_NO_LEVEL_CROSSING) ? 'l' : '-',
2176 HasBit(rti->flags, ROTF_NO_HOUSES) ? 'X' : '-',
2177 HasBit(rti->flags, ROTF_HIDDEN) ? 'h' : '-',
2178 HasBit(rti->flags, ROTF_TOWN_BUILD) ? 'T' : '-',
2179 BSWAP32(grfid),
2180 GetStringPtr(rti->strings.name)
2183 for (const auto &grf : grfs) {
2184 IConsolePrint(CC_DEFAULT, " GRF: {:08X} = {}", BSWAP32(grf.first), grf.second->filename);
2188 static void ConDumpRailTypes()
2190 IConsolePrint(CC_DEFAULT, " Flags:");
2191 IConsolePrint(CC_DEFAULT, " c = catenary");
2192 IConsolePrint(CC_DEFAULT, " l = no level crossings");
2193 IConsolePrint(CC_DEFAULT, " h = hidden");
2194 IConsolePrint(CC_DEFAULT, " s = no sprite combine");
2195 IConsolePrint(CC_DEFAULT, " a = always allow 90 degree turns");
2196 IConsolePrint(CC_DEFAULT, " d = always disallow 90 degree turns");
2198 std::map<uint32, const GRFFile *> grfs;
2199 for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
2200 const RailtypeInfo *rti = GetRailTypeInfo(rt);
2201 if (rti->label == 0) continue;
2202 uint32 grfid = 0;
2203 const GRFFile *grf = rti->grffile[RTSG_GROUND];
2204 if (grf != nullptr) {
2205 grfid = grf->grfid;
2206 grfs.emplace(grfid, grf);
2208 IConsolePrint(CC_DEFAULT, " {:02d} {:c}{:c}{:c}{:c}, Flags: {}{}{}{}{}{}, GRF: {:08X}, {}",
2209 (uint)rt,
2210 rti->label >> 24, rti->label >> 16, rti->label >> 8, rti->label,
2211 HasBit(rti->flags, RTF_CATENARY) ? 'c' : '-',
2212 HasBit(rti->flags, RTF_NO_LEVEL_CROSSING) ? 'l' : '-',
2213 HasBit(rti->flags, RTF_HIDDEN) ? 'h' : '-',
2214 HasBit(rti->flags, RTF_NO_SPRITE_COMBINE) ? 's' : '-',
2215 HasBit(rti->flags, RTF_ALLOW_90DEG) ? 'a' : '-',
2216 HasBit(rti->flags, RTF_DISALLOW_90DEG) ? 'd' : '-',
2217 BSWAP32(grfid),
2218 GetStringPtr(rti->strings.name)
2221 for (const auto &grf : grfs) {
2222 IConsolePrint(CC_DEFAULT, " GRF: {:08X} = {}", BSWAP32(grf.first), grf.second->filename);
2226 static void ConDumpCargoTypes()
2228 IConsolePrint(CC_DEFAULT, " Cargo classes:");
2229 IConsolePrint(CC_DEFAULT, " p = passenger");
2230 IConsolePrint(CC_DEFAULT, " m = mail");
2231 IConsolePrint(CC_DEFAULT, " x = express");
2232 IConsolePrint(CC_DEFAULT, " a = armoured");
2233 IConsolePrint(CC_DEFAULT, " b = bulk");
2234 IConsolePrint(CC_DEFAULT, " g = piece goods");
2235 IConsolePrint(CC_DEFAULT, " l = liquid");
2236 IConsolePrint(CC_DEFAULT, " r = refrigerated");
2237 IConsolePrint(CC_DEFAULT, " h = hazardous");
2238 IConsolePrint(CC_DEFAULT, " c = covered/sheltered");
2239 IConsolePrint(CC_DEFAULT, " S = special");
2241 std::map<uint32, const GRFFile *> grfs;
2242 for (CargoID i = 0; i < NUM_CARGO; i++) {
2243 const CargoSpec *spec = CargoSpec::Get(i);
2244 if (!spec->IsValid()) continue;
2245 uint32 grfid = 0;
2246 const GRFFile *grf = spec->grffile;
2247 if (grf != nullptr) {
2248 grfid = grf->grfid;
2249 grfs.emplace(grfid, grf);
2251 IConsolePrint(CC_DEFAULT, " {:02d} Bit: {:2d}, Label: {:c}{:c}{:c}{:c}, Callback mask: 0x{:02X}, Cargo class: {}{}{}{}{}{}{}{}{}{}{}, GRF: {:08X}, {}",
2252 (uint)i,
2253 spec->bitnum,
2254 spec->label >> 24, spec->label >> 16, spec->label >> 8, spec->label,
2255 spec->callback_mask,
2256 (spec->classes & CC_PASSENGERS) != 0 ? 'p' : '-',
2257 (spec->classes & CC_MAIL) != 0 ? 'm' : '-',
2258 (spec->classes & CC_EXPRESS) != 0 ? 'x' : '-',
2259 (spec->classes & CC_ARMOURED) != 0 ? 'a' : '-',
2260 (spec->classes & CC_BULK) != 0 ? 'b' : '-',
2261 (spec->classes & CC_PIECE_GOODS) != 0 ? 'g' : '-',
2262 (spec->classes & CC_LIQUID) != 0 ? 'l' : '-',
2263 (spec->classes & CC_REFRIGERATED) != 0 ? 'r' : '-',
2264 (spec->classes & CC_HAZARDOUS) != 0 ? 'h' : '-',
2265 (spec->classes & CC_COVERED) != 0 ? 'c' : '-',
2266 (spec->classes & CC_SPECIAL) != 0 ? 'S' : '-',
2267 BSWAP32(grfid),
2268 GetStringPtr(spec->name)
2271 for (const auto &grf : grfs) {
2272 IConsolePrint(CC_DEFAULT, " GRF: {:08X} = {}", BSWAP32(grf.first), grf.second->filename);
2277 DEF_CONSOLE_CMD(ConDumpInfo)
2279 if (argc != 2) {
2280 IConsolePrint(CC_HELP, "Dump debugging information.");
2281 IConsolePrint(CC_HELP, "Usage: 'dump_info roadtypes|railtypes|cargotypes'.");
2282 IConsolePrint(CC_HELP, " Show information about road/tram types, rail types or cargo types.");
2283 return true;
2286 if (strcasecmp(argv[1], "roadtypes") == 0) {
2287 ConDumpRoadTypes();
2288 return true;
2291 if (strcasecmp(argv[1], "railtypes") == 0) {
2292 ConDumpRailTypes();
2293 return true;
2296 if (strcasecmp(argv[1], "cargotypes") == 0) {
2297 ConDumpCargoTypes();
2298 return true;
2301 return false;
2304 /*******************************
2305 * console command registration
2306 *******************************/
2308 void IConsoleStdLibRegister()
2310 IConsole::CmdRegister("debug_level", ConDebugLevel);
2311 IConsole::CmdRegister("echo", ConEcho);
2312 IConsole::CmdRegister("echoc", ConEchoC);
2313 IConsole::CmdRegister("exec", ConExec);
2314 IConsole::CmdRegister("exit", ConExit);
2315 IConsole::CmdRegister("part", ConPart);
2316 IConsole::CmdRegister("help", ConHelp);
2317 IConsole::CmdRegister("info_cmd", ConInfoCmd);
2318 IConsole::CmdRegister("list_cmds", ConListCommands);
2319 IConsole::CmdRegister("list_aliases", ConListAliases);
2320 IConsole::CmdRegister("newgame", ConNewGame);
2321 IConsole::CmdRegister("restart", ConRestart);
2322 IConsole::CmdRegister("reload", ConReload);
2323 IConsole::CmdRegister("getseed", ConGetSeed);
2324 IConsole::CmdRegister("getdate", ConGetDate);
2325 IConsole::CmdRegister("getsysdate", ConGetSysDate);
2326 IConsole::CmdRegister("quit", ConExit);
2327 IConsole::CmdRegister("resetengines", ConResetEngines, ConHookNoNetwork);
2328 IConsole::CmdRegister("reset_enginepool", ConResetEnginePool, ConHookNoNetwork);
2329 IConsole::CmdRegister("return", ConReturn);
2330 IConsole::CmdRegister("screenshot", ConScreenShot);
2331 IConsole::CmdRegister("script", ConScript);
2332 IConsole::CmdRegister("scrollto", ConScrollToTile);
2333 IConsole::CmdRegister("alias", ConAlias);
2334 IConsole::CmdRegister("load", ConLoad);
2335 IConsole::CmdRegister("rm", ConRemove);
2336 IConsole::CmdRegister("save", ConSave);
2337 IConsole::CmdRegister("saveconfig", ConSaveConfig);
2338 IConsole::CmdRegister("ls", ConListFiles);
2339 IConsole::CmdRegister("cd", ConChangeDirectory);
2340 IConsole::CmdRegister("pwd", ConPrintWorkingDirectory);
2341 IConsole::CmdRegister("clear", ConClearBuffer);
2342 IConsole::CmdRegister("setting", ConSetting);
2343 IConsole::CmdRegister("setting_newgame", ConSettingNewgame);
2344 IConsole::CmdRegister("list_settings", ConListSettings);
2345 IConsole::CmdRegister("gamelog", ConGamelogPrint);
2346 IConsole::CmdRegister("rescan_newgrf", ConRescanNewGRF);
2348 IConsole::AliasRegister("dir", "ls");
2349 IConsole::AliasRegister("del", "rm %+");
2350 IConsole::AliasRegister("newmap", "newgame");
2351 IConsole::AliasRegister("patch", "setting %+");
2352 IConsole::AliasRegister("set", "setting %+");
2353 IConsole::AliasRegister("set_newgame", "setting_newgame %+");
2354 IConsole::AliasRegister("list_patches", "list_settings %+");
2355 IConsole::AliasRegister("developer", "setting developer %+");
2357 IConsole::CmdRegister("list_ai_libs", ConListAILibs);
2358 IConsole::CmdRegister("list_ai", ConListAI);
2359 IConsole::CmdRegister("reload_ai", ConReloadAI);
2360 IConsole::CmdRegister("rescan_ai", ConRescanAI);
2361 IConsole::CmdRegister("start_ai", ConStartAI);
2362 IConsole::CmdRegister("stop_ai", ConStopAI);
2364 IConsole::CmdRegister("list_game", ConListGame);
2365 IConsole::CmdRegister("list_game_libs", ConListGameLibs);
2366 IConsole::CmdRegister("rescan_game", ConRescanGame);
2368 IConsole::CmdRegister("companies", ConCompanies);
2369 IConsole::AliasRegister("players", "companies");
2371 /* networking functions */
2373 /* Content downloading is only available with ZLIB */
2374 #if defined(WITH_ZLIB)
2375 IConsole::CmdRegister("content", ConContent);
2376 #endif /* defined(WITH_ZLIB) */
2378 /*** Networking commands ***/
2379 IConsole::CmdRegister("say", ConSay, ConHookNeedNetwork);
2380 IConsole::CmdRegister("say_company", ConSayCompany, ConHookNeedNetwork);
2381 IConsole::AliasRegister("say_player", "say_company %+");
2382 IConsole::CmdRegister("say_client", ConSayClient, ConHookNeedNetwork);
2384 IConsole::CmdRegister("connect", ConNetworkConnect, ConHookClientOnly);
2385 IConsole::CmdRegister("clients", ConNetworkClients, ConHookNeedNetwork);
2386 IConsole::CmdRegister("status", ConStatus, ConHookServerOnly);
2387 IConsole::CmdRegister("server_info", ConServerInfo, ConHookServerOnly);
2388 IConsole::AliasRegister("info", "server_info");
2389 IConsole::CmdRegister("reconnect", ConNetworkReconnect, ConHookClientOnly);
2390 IConsole::CmdRegister("rcon", ConRcon, ConHookNeedNetwork);
2392 IConsole::CmdRegister("join", ConJoinCompany, ConHookNeedNetwork);
2393 IConsole::AliasRegister("spectate", "join 255");
2394 IConsole::CmdRegister("move", ConMoveClient, ConHookServerOnly);
2395 IConsole::CmdRegister("reset_company", ConResetCompany, ConHookServerOnly);
2396 IConsole::AliasRegister("clean_company", "reset_company %A");
2397 IConsole::CmdRegister("client_name", ConClientNickChange, ConHookServerOnly);
2398 IConsole::CmdRegister("kick", ConKick, ConHookServerOnly);
2399 IConsole::CmdRegister("ban", ConBan, ConHookServerOnly);
2400 IConsole::CmdRegister("unban", ConUnBan, ConHookServerOnly);
2401 IConsole::CmdRegister("banlist", ConBanList, ConHookServerOnly);
2403 IConsole::CmdRegister("pause", ConPauseGame, ConHookServerOrNoNetwork);
2404 IConsole::CmdRegister("unpause", ConUnpauseGame, ConHookServerOrNoNetwork);
2406 IConsole::CmdRegister("company_pw", ConCompanyPassword, ConHookNeedNetwork);
2407 IConsole::AliasRegister("company_password", "company_pw %+");
2409 IConsole::AliasRegister("net_frame_freq", "setting frame_freq %+");
2410 IConsole::AliasRegister("net_sync_freq", "setting sync_freq %+");
2411 IConsole::AliasRegister("server_pw", "setting server_password %+");
2412 IConsole::AliasRegister("server_password", "setting server_password %+");
2413 IConsole::AliasRegister("rcon_pw", "setting rcon_password %+");
2414 IConsole::AliasRegister("rcon_password", "setting rcon_password %+");
2415 IConsole::AliasRegister("name", "setting client_name %+");
2416 IConsole::AliasRegister("server_name", "setting server_name %+");
2417 IConsole::AliasRegister("server_port", "setting server_port %+");
2418 IConsole::AliasRegister("max_clients", "setting max_clients %+");
2419 IConsole::AliasRegister("max_companies", "setting max_companies %+");
2420 IConsole::AliasRegister("max_join_time", "setting max_join_time %+");
2421 IConsole::AliasRegister("pause_on_join", "setting pause_on_join %+");
2422 IConsole::AliasRegister("autoclean_companies", "setting autoclean_companies %+");
2423 IConsole::AliasRegister("autoclean_protected", "setting autoclean_protected %+");
2424 IConsole::AliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2425 IConsole::AliasRegister("restart_game_year", "setting restart_game_year %+");
2426 IConsole::AliasRegister("min_players", "setting min_active_clients %+");
2427 IConsole::AliasRegister("reload_cfg", "setting reload_cfg %+");
2429 /* debugging stuff */
2430 #ifdef _DEBUG
2431 IConsoleDebugLibRegister();
2432 #endif
2433 IConsole::CmdRegister("fps", ConFramerate);
2434 IConsole::CmdRegister("fps_wnd", ConFramerateWindow);
2436 /* NewGRF development stuff */
2437 IConsole::CmdRegister("reload_newgrfs", ConNewGRFReload, ConHookNewGRFDeveloperTool);
2438 IConsole::CmdRegister("newgrf_profile", ConNewGRFProfile, ConHookNewGRFDeveloperTool);
2440 IConsole::CmdRegister("dump_info", ConDumpInfo);