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/>.
8 /** @file console_cmds.cpp Implementation of the console hooks. */
11 #include "console_internal.h"
13 #include "engine_func.h"
14 #include "landscape.h"
15 #include "saveload/saveload.h"
16 #include "network/network.h"
17 #include "network/network_func.h"
18 #include "network/network_base.h"
19 #include "network/network_admin.h"
20 #include "network/network_client.h"
21 #include "command_func.h"
22 #include "settings_func.h"
24 #include "fileio_func.h"
25 #include "screenshot.h"
27 #include "strings_func.h"
28 #include "viewport_func.h"
29 #include "window_func.h"
30 #include "date_func.h"
31 #include "company_func.h"
34 #include "ai/ai_config.hpp"
36 #include "newgrf_profiling.h"
37 #include "console_func.h"
38 #include "engine_base.h"
39 #include "game/game.hpp"
40 #include "table/strings.h"
43 #include "safeguards.h"
45 /* scriptfile handling */
46 static bool _script_running
; ///< Script is running (used to abort execution when #ConReturn is encountered).
48 /** File list storage for the console, for caching the last 'ls' command. */
49 class ConsoleFileList
: public FileList
{
51 ConsoleFileList() : FileList()
53 this->file_list_valid
= false;
56 /** Declare the file storage cache as being invalid, also clears all stored files. */
57 void InvalidateFileList()
60 this->file_list_valid
= false;
64 * (Re-)validate the file storage cache. Only makes a change if the storage was invalid, or if \a force_reload.
65 * @param force_reload Always reload the file storage cache.
67 void ValidateFileList(bool force_reload
= false)
69 if (force_reload
|| !this->file_list_valid
) {
70 this->BuildFileList(FT_SAVEGAME
, SLO_LOAD
);
71 this->file_list_valid
= true;
75 bool file_list_valid
; ///< If set, the file list is valid.
78 static ConsoleFileList _console_file_list
; ///< File storage cache for the console.
80 /* console command defines */
81 #define DEF_CONSOLE_CMD(function) static bool function(byte argc, char *argv[])
82 #define DEF_CONSOLE_HOOK(function) static ConsoleHookResult function(bool echo)
90 * Check network availability and inform in console about failure of detection.
91 * @return Network availability.
93 static inline bool NetworkAvailable(bool echo
)
95 if (!_network_available
) {
96 if (echo
) IConsoleError("You cannot use this command because there is no network available.");
103 * Check whether we are a server.
104 * @return Are we a server? True when yes, false otherwise.
106 DEF_CONSOLE_HOOK(ConHookServerOnly
)
108 if (!NetworkAvailable(echo
)) return CHR_DISALLOW
;
110 if (!_network_server
) {
111 if (echo
) IConsoleError("This command is only available to a network server.");
118 * Check whether we are a client in a network game.
119 * @return Are we a client in a network game? True when yes, false otherwise.
121 DEF_CONSOLE_HOOK(ConHookClientOnly
)
123 if (!NetworkAvailable(echo
)) return CHR_DISALLOW
;
125 if (_network_server
) {
126 if (echo
) IConsoleError("This command is not available to a network server.");
133 * Check whether we are in a multiplayer game.
134 * @return True when we are client or server in a network game.
136 DEF_CONSOLE_HOOK(ConHookNeedNetwork
)
138 if (!NetworkAvailable(echo
)) return CHR_DISALLOW
;
140 if (!_networking
|| (!_network_server
&& !MyClient::IsConnected())) {
141 if (echo
) IConsoleError("Not connected. This command is only available in multiplayer.");
148 * Check whether we are in single player mode.
149 * @return True when no network is active.
151 DEF_CONSOLE_HOOK(ConHookNoNetwork
)
154 if (echo
) IConsoleError("This command is forbidden in multiplayer.");
160 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool
)
162 if (_settings_client
.gui
.newgrf_developer_tools
) {
163 if (_game_mode
== GM_MENU
) {
164 if (echo
) IConsoleError("This command is only available in game and editor.");
167 return ConHookNoNetwork(echo
);
173 * Show help for the console.
174 * @param str String to print in the console.
176 static void IConsoleHelp(const char *str
)
178 IConsolePrintF(CC_WARNING
, "- %s", str
);
182 * Reset status of all engines.
183 * @return Will always succeed.
185 DEF_CONSOLE_CMD(ConResetEngines
)
188 IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'");
197 * Reset status of the engine pool.
198 * @return Will always return true.
199 * @note Resetting the pool only succeeds when there are no vehicles ingame.
201 DEF_CONSOLE_CMD(ConResetEnginePool
)
204 IConsoleHelp("Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
208 if (_game_mode
== GM_MENU
) {
209 IConsoleError("This command is only available in game and editor.");
213 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
214 IConsoleError("This can only be done when there are no vehicles in the game.");
223 * Reset a tile to bare land in debug mode.
225 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
227 DEF_CONSOLE_CMD(ConResetTile
)
230 IConsoleHelp("Reset a tile to bare land. Usage: 'resettile <tile>'");
231 IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)");
237 if (GetArgumentInteger(&result
, argv
[1])) {
238 DoClearSquare((TileIndex
)result
);
248 * Scroll to a tile on the map.
249 * param x tile number or tile x coordinate.
250 * param y optional y coordinate.
251 * @note When only one argument is given it is interpreted as the tile number.
252 * When two arguments are given, they are interpreted as the tile's x
254 * @return True when either console help was shown or a proper amount of parameters given.
256 DEF_CONSOLE_CMD(ConScrollToTile
)
260 IConsoleHelp("Center the screen on a given tile.");
261 IConsoleHelp("Usage: 'scrollto <tile>' or 'scrollto <x> <y>'");
262 IConsoleHelp("Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
267 if (GetArgumentInteger(&result
, argv
[1])) {
268 if (result
>= MapSize()) {
269 IConsolePrint(CC_ERROR
, "Tile does not exist");
272 ScrollMainWindowToTile((TileIndex
)result
);
280 if (GetArgumentInteger(&x
, argv
[1]) && GetArgumentInteger(&y
, argv
[2])) {
281 if (x
>= MapSizeX() || y
>= MapSizeY()) {
282 IConsolePrint(CC_ERROR
, "Tile does not exist");
285 ScrollMainWindowToTile(TileXY(x
, y
));
296 * Save the map to a file.
297 * param filename the filename to save the map to.
298 * @return True when help was displayed or the file attempted to be saved.
300 DEF_CONSOLE_CMD(ConSave
)
303 IConsoleHelp("Save the current game. Usage: 'save <filename>'");
308 char *filename
= str_fmt("%s.sav", argv
[1]);
309 IConsolePrint(CC_DEFAULT
, "Saving map...");
311 if (SaveOrLoad(filename
, SLO_SAVE
, DFT_GAME_FILE
, SAVE_DIR
) != SL_OK
) {
312 IConsolePrint(CC_ERROR
, "Saving map failed");
314 IConsolePrintF(CC_DEFAULT
, "Map successfully saved to %s", filename
);
324 * Explicitly save the configuration.
327 DEF_CONSOLE_CMD(ConSaveConfig
)
330 IConsoleHelp("Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
331 IConsoleHelp("It does not save the configuration of the current game to the configuration file.");
336 IConsolePrint(CC_DEFAULT
, "Saved config.");
340 DEF_CONSOLE_CMD(ConLoad
)
343 IConsoleHelp("Load a game by name or index. Usage: 'load <file | number>'");
347 if (argc
!= 2) return false;
349 const char *file
= argv
[1];
350 _console_file_list
.ValidateFileList();
351 const FiosItem
*item
= _console_file_list
.FindItem(file
);
352 if (item
!= nullptr) {
353 if (GetAbstractFileType(item
->type
) == FT_SAVEGAME
) {
354 _switch_mode
= SM_LOAD_GAME
;
355 _file_to_saveload
.SetMode(item
->type
);
356 _file_to_saveload
.SetName(FiosBrowseTo(item
));
357 _file_to_saveload
.SetTitle(item
->title
);
359 IConsolePrintF(CC_ERROR
, "%s: Not a savegame.", file
);
362 IConsolePrintF(CC_ERROR
, "%s: No such file or directory.", file
);
369 DEF_CONSOLE_CMD(ConRemove
)
372 IConsoleHelp("Remove a savegame by name or index. Usage: 'rm <file | number>'");
376 if (argc
!= 2) return false;
378 const char *file
= argv
[1];
379 _console_file_list
.ValidateFileList();
380 const FiosItem
*item
= _console_file_list
.FindItem(file
);
381 if (item
!= nullptr) {
382 if (!FiosDelete(item
->name
)) {
383 IConsolePrintF(CC_ERROR
, "%s: Failed to delete file", file
);
386 IConsolePrintF(CC_ERROR
, "%s: No such file or directory.", file
);
389 _console_file_list
.InvalidateFileList();
394 /* List all the files in the current dir via console */
395 DEF_CONSOLE_CMD(ConListFiles
)
398 IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'");
402 _console_file_list
.ValidateFileList(true);
403 for (uint i
= 0; i
< _console_file_list
.Length(); i
++) {
404 IConsolePrintF(CC_DEFAULT
, "%d) %s", i
, _console_file_list
[i
].title
);
410 /* Change the dir via console */
411 DEF_CONSOLE_CMD(ConChangeDirectory
)
414 IConsoleHelp("Change the dir via console. Usage: 'cd <directory | number>'");
418 if (argc
!= 2) return false;
420 const char *file
= argv
[1];
421 _console_file_list
.ValidateFileList(true);
422 const FiosItem
*item
= _console_file_list
.FindItem(file
);
423 if (item
!= nullptr) {
424 switch (item
->type
) {
425 case FIOS_TYPE_DIR
: case FIOS_TYPE_DRIVE
: case FIOS_TYPE_PARENT
:
428 default: IConsolePrintF(CC_ERROR
, "%s: Not a directory.", file
);
431 IConsolePrintF(CC_ERROR
, "%s: No such file or directory.", file
);
434 _console_file_list
.InvalidateFileList();
438 DEF_CONSOLE_CMD(ConPrintWorkingDirectory
)
443 IConsoleHelp("Print out the current working directory. Usage: 'pwd'");
447 /* XXX - Workaround for broken file handling */
448 _console_file_list
.ValidateFileList(true);
449 _console_file_list
.InvalidateFileList();
451 FiosGetDescText(&path
, nullptr);
452 IConsolePrint(CC_DEFAULT
, path
);
456 DEF_CONSOLE_CMD(ConClearBuffer
)
459 IConsoleHelp("Clear the console buffer. Usage: 'clear'");
463 IConsoleClearBuffer();
464 SetWindowDirty(WC_CONSOLE
, 0);
469 /**********************************
470 * Network Core Console Commands
471 **********************************/
473 static bool ConKickOrBan(const char *argv
, bool ban
, const char *reason
)
477 if (strchr(argv
, '.') == nullptr && strchr(argv
, ':') == nullptr) { // banning with ID
478 ClientID client_id
= (ClientID
)atoi(argv
);
480 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
481 * kicking frees closes and subsequently free the connection related instances, which we
482 * would be reading from and writing to after returning. So we would read or write data
483 * from freed memory up till the segfault triggers. */
484 if (client_id
== CLIENT_ID_SERVER
|| client_id
== _redirect_console_to_client
) {
485 IConsolePrintF(CC_ERROR
, "ERROR: Silly boy, you can not %s yourself!", ban
? "ban" : "kick");
489 NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(client_id
);
491 IConsoleError("Invalid client");
496 /* Kick only this client, not all clients with that IP */
497 NetworkServerKickClient(client_id
, reason
);
501 /* When banning, kick+ban all clients with that IP */
502 n
= NetworkServerKickOrBanIP(client_id
, ban
, reason
);
504 n
= NetworkServerKickOrBanIP(argv
, ban
, reason
);
508 IConsolePrint(CC_DEFAULT
, ban
? "Client not online, address added to banlist" : "Client not found");
510 IConsolePrintF(CC_DEFAULT
, "%sed %u client(s)", ban
? "Bann" : "Kick", n
);
516 DEF_CONSOLE_CMD(ConKick
)
519 IConsoleHelp("Kick a client from a network game. Usage: 'kick <ip | client-id> [<kick-reason>]'");
520 IConsoleHelp("For client-id's, see the command 'clients'");
524 if (argc
!= 2 && argc
!= 3) return false;
526 /* No reason supplied for kicking */
527 if (argc
== 2) return ConKickOrBan(argv
[1], false, nullptr);
529 /* Reason for kicking supplied */
530 size_t kick_message_length
= strlen(argv
[2]);
531 if (kick_message_length
>= 255) {
532 IConsolePrintF(CC_ERROR
, "ERROR: Maximum kick message length is 254 characters. You entered " PRINTF_SIZE
" characters.", kick_message_length
);
535 return ConKickOrBan(argv
[1], false, argv
[2]);
539 DEF_CONSOLE_CMD(ConBan
)
542 IConsoleHelp("Ban a client from a network game. Usage: 'ban <ip | client-id> [<ban-reason>]'");
543 IConsoleHelp("For client-id's, see the command 'clients'");
544 IConsoleHelp("If the client is no longer online, you can still ban his/her IP");
548 if (argc
!= 2 && argc
!= 3) return false;
550 /* No reason supplied for kicking */
551 if (argc
== 2) return ConKickOrBan(argv
[1], true, nullptr);
553 /* Reason for kicking supplied */
554 size_t kick_message_length
= strlen(argv
[2]);
555 if (kick_message_length
>= 255) {
556 IConsolePrintF(CC_ERROR
, "ERROR: Maximum kick message length is 254 characters. You entered " PRINTF_SIZE
" characters.", kick_message_length
);
559 return ConKickOrBan(argv
[1], true, argv
[2]);
563 DEF_CONSOLE_CMD(ConUnBan
)
566 IConsoleHelp("Unban a client from a network game. Usage: 'unban <ip | banlist-index>'");
567 IConsoleHelp("For a list of banned IP's, see the command 'banlist'");
571 if (argc
!= 2) return false;
575 for (index
= 0; index
< _network_ban_list
.size(); index
++) {
576 if (_network_ban_list
[index
] == argv
[1]) break;
580 if (index
>= _network_ban_list
.size()) {
581 index
= atoi(argv
[1]) - 1U; // let it wrap
584 if (index
< _network_ban_list
.size()) {
586 seprintf(msg
, lastof(msg
), "Unbanned %s", _network_ban_list
[index
].c_str());
587 IConsolePrint(CC_DEFAULT
, msg
);
588 _network_ban_list
.erase(_network_ban_list
.begin() + index
);
590 IConsolePrint(CC_DEFAULT
, "Invalid list index or IP not in ban-list.");
591 IConsolePrint(CC_DEFAULT
, "For a list of banned IP's, see the command 'banlist'");
597 DEF_CONSOLE_CMD(ConBanList
)
600 IConsoleHelp("List the IP's of banned clients: Usage 'banlist'");
604 IConsolePrint(CC_DEFAULT
, "Banlist: ");
607 for (const auto &entry
: _network_ban_list
) {
608 IConsolePrintF(CC_DEFAULT
, " %d) %s", i
, entry
.c_str());
614 DEF_CONSOLE_CMD(ConPauseGame
)
617 IConsoleHelp("Pause a network game. Usage: 'pause'");
621 if ((_pause_mode
& PM_PAUSED_NORMAL
) == PM_UNPAUSED
) {
622 DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
623 if (!_networking
) IConsolePrint(CC_DEFAULT
, "Game paused.");
625 IConsolePrint(CC_DEFAULT
, "Game is already paused.");
631 DEF_CONSOLE_CMD(ConUnpauseGame
)
634 IConsoleHelp("Unpause a network game. Usage: 'unpause'");
638 if ((_pause_mode
& PM_PAUSED_NORMAL
) != PM_UNPAUSED
) {
639 DoCommandP(0, PM_PAUSED_NORMAL
, 0, CMD_PAUSE
);
640 if (!_networking
) IConsolePrint(CC_DEFAULT
, "Game unpaused.");
641 } else if ((_pause_mode
& PM_PAUSED_ERROR
) != PM_UNPAUSED
) {
642 IConsolePrint(CC_DEFAULT
, "Game is in error state and cannot be unpaused via console.");
643 } else if (_pause_mode
!= PM_UNPAUSED
) {
644 IConsolePrint(CC_DEFAULT
, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
646 IConsolePrint(CC_DEFAULT
, "Game is already unpaused.");
652 DEF_CONSOLE_CMD(ConRcon
)
655 IConsoleHelp("Remote control the server from another client. Usage: 'rcon <password> <command>'");
656 IConsoleHelp("Remember to enclose the command in quotes, otherwise only the first parameter is sent");
660 if (argc
< 3) return false;
662 if (_network_server
) {
663 IConsoleCmdExec(argv
[2]);
665 NetworkClientSendRcon(argv
[1], argv
[2]);
670 DEF_CONSOLE_CMD(ConStatus
)
673 IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
677 NetworkServerShowStatusToConsole();
681 DEF_CONSOLE_CMD(ConServerInfo
)
684 IConsoleHelp("List current and maximum client/company limits. Usage 'server_info'");
685 IConsoleHelp("You can change these values by modifying settings 'network.max_clients', 'network.max_companies' and 'network.max_spectators'");
689 IConsolePrintF(CC_DEFAULT
, "Current/maximum clients: %2d/%2d", _network_game_info
.clients_on
, _settings_client
.network
.max_clients
);
690 IConsolePrintF(CC_DEFAULT
, "Current/maximum companies: %2d/%2d", (int)Company::GetNumItems(), _settings_client
.network
.max_companies
);
691 IConsolePrintF(CC_DEFAULT
, "Current/maximum spectators: %2d/%2d", NetworkSpectatorCount(), _settings_client
.network
.max_spectators
);
696 DEF_CONSOLE_CMD(ConClientNickChange
)
699 IConsoleHelp("Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'");
700 IConsoleHelp("For client-id's, see the command 'clients'");
704 ClientID client_id
= (ClientID
)atoi(argv
[1]);
706 if (client_id
== CLIENT_ID_SERVER
) {
707 IConsoleError("Please use the command 'name' to change your own name!");
711 if (NetworkClientInfo::GetByClientID(client_id
) == nullptr) {
712 IConsoleError("Invalid client");
716 if (!NetworkServerChangeClientName(client_id
, argv
[2])) {
717 IConsoleError("Cannot give a client a duplicate name");
723 DEF_CONSOLE_CMD(ConJoinCompany
)
726 IConsoleHelp("Request joining another company. Usage: join <company-id> [<password>]");
727 IConsoleHelp("For valid company-id see company list, use 255 for spectator");
731 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) <= MAX_COMPANIES
? atoi(argv
[1]) - 1 : atoi(argv
[1]));
733 /* Check we have a valid company id! */
734 if (!Company::IsValidID(company_id
) && company_id
!= COMPANY_SPECTATOR
) {
735 IConsolePrintF(CC_ERROR
, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES
);
739 if (NetworkClientInfo::GetByClientID(_network_own_client_id
)->client_playas
== company_id
) {
740 IConsoleError("You are already there!");
744 if (company_id
== COMPANY_SPECTATOR
&& NetworkMaxSpectatorsReached()) {
745 IConsoleError("Cannot join spectators, maximum number of spectators reached.");
749 if (company_id
!= COMPANY_SPECTATOR
&& !Company::IsHumanID(company_id
)) {
750 IConsoleError("Cannot join AI company.");
754 /* Check if the company requires a password */
755 if (NetworkCompanyIsPassworded(company_id
) && argc
< 3) {
756 IConsolePrintF(CC_ERROR
, "Company %d requires a password to join.", company_id
+ 1);
760 /* non-dedicated server may just do the move! */
761 if (_network_server
) {
762 NetworkServerDoMove(CLIENT_ID_SERVER
, company_id
);
764 NetworkClientRequestMove(company_id
, NetworkCompanyIsPassworded(company_id
) ? argv
[2] : "");
770 DEF_CONSOLE_CMD(ConMoveClient
)
773 IConsoleHelp("Move a client to another company. Usage: move <client-id> <company-id>");
774 IConsoleHelp("For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators");
778 const NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID((ClientID
)atoi(argv
[1]));
779 CompanyID company_id
= (CompanyID
)(atoi(argv
[2]) <= MAX_COMPANIES
? atoi(argv
[2]) - 1 : atoi(argv
[2]));
781 /* check the client exists */
783 IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
787 if (!Company::IsValidID(company_id
) && company_id
!= COMPANY_SPECTATOR
) {
788 IConsolePrintF(CC_ERROR
, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES
);
792 if (company_id
!= COMPANY_SPECTATOR
&& !Company::IsHumanID(company_id
)) {
793 IConsoleError("You cannot move clients to AI companies.");
797 if (ci
->client_id
== CLIENT_ID_SERVER
&& _network_dedicated
) {
798 IConsoleError("Silly boy, you cannot move the server!");
802 if (ci
->client_playas
== company_id
) {
803 IConsoleError("You cannot move someone to where he/she already is!");
807 /* we are the server, so force the update */
808 NetworkServerDoMove(ci
->client_id
, company_id
);
813 DEF_CONSOLE_CMD(ConResetCompany
)
816 IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company <company-id>'");
817 IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
821 if (argc
!= 2) return false;
823 CompanyID index
= (CompanyID
)(atoi(argv
[1]) - 1);
825 /* Check valid range */
826 if (!Company::IsValidID(index
)) {
827 IConsolePrintF(CC_ERROR
, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES
);
831 if (!Company::IsHumanID(index
)) {
832 IConsoleError("Company is owned by an AI.");
836 if (NetworkCompanyHasClients(index
)) {
837 IConsoleError("Cannot remove company: a client is connected to that company.");
840 const NetworkClientInfo
*ci
= NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER
);
841 if (ci
->client_playas
== index
) {
842 IConsoleError("Cannot remove company: the server is connected to that company.");
846 /* It is safe to remove this company */
847 DoCommandP(0, CCA_DELETE
| index
<< 16 | CRR_MANUAL
<< 24, 0, CMD_COMPANY_CTRL
);
848 IConsolePrint(CC_DEFAULT
, "Company deleted.");
853 DEF_CONSOLE_CMD(ConNetworkClients
)
856 IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'");
860 NetworkPrintClients();
865 DEF_CONSOLE_CMD(ConNetworkReconnect
)
868 IConsoleHelp("Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'");
869 IConsoleHelp("Company 255 is spectator (default, if not specified), 0 means creating new company.");
870 IConsoleHelp("All others are a certain company with Company 1 being #1");
874 CompanyID playas
= (argc
>= 2) ? (CompanyID
)atoi(argv
[1]) : COMPANY_SPECTATOR
;
876 case 0: playas
= COMPANY_NEW_COMPANY
; break;
877 case COMPANY_SPECTATOR
: /* nothing to do */ break;
879 /* From a user pov 0 is a new company, internally it's different and all
880 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
881 if (playas
< COMPANY_FIRST
+ 1 || playas
> MAX_COMPANIES
+ 1) return false;
885 if (StrEmpty(_settings_client
.network
.last_host
)) {
886 IConsolePrint(CC_DEFAULT
, "No server for reconnecting.");
890 /* Don't resolve the address first, just print it directly as it comes from the config file. */
891 IConsolePrintF(CC_DEFAULT
, "Reconnecting to %s:%d...", _settings_client
.network
.last_host
, _settings_client
.network
.last_port
);
893 NetworkClientConnectGame(NetworkAddress(_settings_client
.network
.last_host
, _settings_client
.network
.last_port
), playas
);
897 DEF_CONSOLE_CMD(ConNetworkConnect
)
900 IConsoleHelp("Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'");
901 IConsoleHelp("IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'");
902 IConsoleHelp("Company #255 is spectator all others are a certain company with Company 1 being #1");
906 if (argc
< 2) return false;
907 if (_networking
) NetworkDisconnect(); // we are in network-mode, first close it!
909 const char *port
= nullptr;
910 const char *company
= nullptr;
912 /* Default settings: default port and new company */
913 uint16 rport
= NETWORK_DEFAULT_PORT
;
914 CompanyID join_as
= COMPANY_NEW_COMPANY
;
916 ParseConnectionString(&company
, &port
, ip
);
918 IConsolePrintF(CC_DEFAULT
, "Connecting to %s...", ip
);
919 if (company
!= nullptr) {
920 join_as
= (CompanyID
)atoi(company
);
921 IConsolePrintF(CC_DEFAULT
, " company-no: %d", join_as
);
923 /* From a user pov 0 is a new company, internally it's different and all
924 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
925 if (join_as
!= COMPANY_SPECTATOR
) {
926 if (join_as
> MAX_COMPANIES
) return false;
930 if (port
!= nullptr) {
932 IConsolePrintF(CC_DEFAULT
, " port: %s", port
);
935 NetworkClientConnectGame(NetworkAddress(ip
, rport
), join_as
);
940 /*********************************
941 * script file console commands
942 *********************************/
944 DEF_CONSOLE_CMD(ConExec
)
947 IConsoleHelp("Execute a local script file. Usage: 'exec <script> <?>'");
951 if (argc
< 2) return false;
953 FILE *script_file
= FioFOpenFile(argv
[1], "r", BASE_DIR
);
955 if (script_file
== nullptr) {
956 if (argc
== 2 || atoi(argv
[2]) != 0) IConsoleError("script file not found");
960 _script_running
= true;
962 char cmdline
[ICON_CMDLN_SIZE
];
963 while (_script_running
&& fgets(cmdline
, sizeof(cmdline
), script_file
) != nullptr) {
964 /* Remove newline characters from the executing script */
965 for (char *cmdptr
= cmdline
; *cmdptr
!= '\0'; cmdptr
++) {
966 if (*cmdptr
== '\n' || *cmdptr
== '\r') {
971 IConsoleCmdExec(cmdline
);
974 if (ferror(script_file
)) {
975 IConsoleError("Encountered error while trying to read from script file");
978 _script_running
= false;
979 FioFCloseFile(script_file
);
983 DEF_CONSOLE_CMD(ConReturn
)
986 IConsoleHelp("Stop executing a running script. Usage: 'return'");
990 _script_running
= false;
994 /*****************************
995 * default console commands
996 ******************************/
997 extern bool CloseConsoleLogIfActive();
999 DEF_CONSOLE_CMD(ConScript
)
1001 extern FILE *_iconsole_output_file
;
1004 IConsoleHelp("Start or stop logging console output to a file. Usage: 'script <filename>'");
1005 IConsoleHelp("If filename is omitted, a running log is stopped if it is active");
1009 if (!CloseConsoleLogIfActive()) {
1010 if (argc
< 2) return false;
1012 IConsolePrintF(CC_DEFAULT
, "file output started to: %s", argv
[1]);
1013 _iconsole_output_file
= fopen(argv
[1], "ab");
1014 if (_iconsole_output_file
== nullptr) IConsoleError("could not open file");
1021 DEF_CONSOLE_CMD(ConEcho
)
1024 IConsoleHelp("Print back the first argument to the console. Usage: 'echo <arg>'");
1028 if (argc
< 2) return false;
1029 IConsolePrint(CC_DEFAULT
, argv
[1]);
1033 DEF_CONSOLE_CMD(ConEchoC
)
1036 IConsoleHelp("Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'");
1040 if (argc
< 3) return false;
1041 IConsolePrint((TextColour
)Clamp(atoi(argv
[1]), TC_BEGIN
, TC_END
- 1), argv
[2]);
1045 DEF_CONSOLE_CMD(ConNewGame
)
1048 IConsoleHelp("Start a new game. Usage: 'newgame [seed]'");
1049 IConsoleHelp("The server can force a new game using 'newgame'; any client joined will rejoin after the server is done generating the new game.");
1053 StartNewGameWithoutGUI((argc
== 2) ? strtoul(argv
[1], nullptr, 10) : GENERATE_NEW_SEED
);
1057 DEF_CONSOLE_CMD(ConRestart
)
1060 IConsoleHelp("Restart game. Usage: 'restart'");
1061 IConsoleHelp("Restarts a game. It tries to reproduce the exact same map as the game started with.");
1062 IConsoleHelp("However:");
1063 IConsoleHelp(" * restarting games started in another version might create another map due to difference in map generation");
1064 IConsoleHelp(" * restarting games based on scenarios, loaded games or heightmaps will start a new game based on the settings stored in the scenario/savegame");
1068 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1069 _settings_game
.game_creation
.map_x
= MapLogX();
1070 _settings_game
.game_creation
.map_y
= FindFirstBit(MapSizeY());
1071 _switch_mode
= SM_RESTARTGAME
;
1076 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1077 * @param buf The buffer to print.
1078 * @note All newlines are replace by '\0' characters.
1080 static void PrintLineByLine(char *buf
)
1083 /* Print output line by line */
1084 for (char *p2
= buf
; *p2
!= '\0'; p2
++) {
1087 IConsolePrintF(CC_DEFAULT
, "%s", p
);
1093 DEF_CONSOLE_CMD(ConListAILibs
)
1096 AI::GetConsoleLibraryList(buf
, lastof(buf
));
1098 PrintLineByLine(buf
);
1103 DEF_CONSOLE_CMD(ConListAI
)
1106 AI::GetConsoleList(buf
, lastof(buf
));
1108 PrintLineByLine(buf
);
1113 DEF_CONSOLE_CMD(ConListGameLibs
)
1116 Game::GetConsoleLibraryList(buf
, lastof(buf
));
1118 PrintLineByLine(buf
);
1123 DEF_CONSOLE_CMD(ConListGame
)
1126 Game::GetConsoleList(buf
, lastof(buf
));
1128 PrintLineByLine(buf
);
1133 DEF_CONSOLE_CMD(ConStartAI
)
1135 if (argc
== 0 || argc
> 3) {
1136 IConsoleHelp("Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'");
1137 IConsoleHelp("Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1138 IConsoleHelp("If <settings> is given, it is parsed and the AI settings are set to that.");
1142 if (_game_mode
!= GM_NORMAL
) {
1143 IConsoleWarning("AIs can only be managed in a game.");
1147 if (Company::GetNumItems() == CompanyPool::MAX_SIZE
) {
1148 IConsoleWarning("Can't start a new AI (no more free slots).");
1151 if (_networking
&& !_network_server
) {
1152 IConsoleWarning("Only the server can start a new AI.");
1155 if (_networking
&& !_settings_game
.ai
.ai_in_multiplayer
) {
1156 IConsoleWarning("AIs are not allowed in multiplayer by configuration.");
1157 IConsoleWarning("Switch AI -> AI in multiplayer to True.");
1160 if (!AI::CanStartNew()) {
1161 IConsoleWarning("Can't start a new AI.");
1166 /* Find the next free slot */
1167 for (const Company
*c
: Company::Iterate()) {
1168 if (c
->index
!= n
) break;
1172 AIConfig
*config
= AIConfig::GetConfig((CompanyID
)n
);
1174 config
->Change(argv
[1], -1, true);
1175 if (!config
->HasScript()) {
1176 IConsoleWarning("Failed to load the specified AI");
1180 config
->StringToSettings(argv
[2]);
1184 /* Start a new AI company */
1185 DoCommandP(0, CCA_NEW_AI
| INVALID_COMPANY
<< 16, 0, CMD_COMPANY_CTRL
);
1190 DEF_CONSOLE_CMD(ConReloadAI
)
1193 IConsoleHelp("Reload an AI. Usage: 'reload_ai <company-id>'");
1194 IConsoleHelp("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.");
1198 if (_game_mode
!= GM_NORMAL
) {
1199 IConsoleWarning("AIs can only be managed in a game.");
1203 if (_networking
&& !_network_server
) {
1204 IConsoleWarning("Only the server can reload an AI.");
1208 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1209 if (!Company::IsValidID(company_id
)) {
1210 IConsolePrintF(CC_DEFAULT
, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES
);
1214 if (Company::IsHumanID(company_id
)) {
1215 IConsoleWarning("Company is not controlled by an AI.");
1219 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1220 DoCommandP(0, CCA_DELETE
| company_id
<< 16 | CRR_MANUAL
<< 24, 0,CMD_COMPANY_CTRL
);
1221 DoCommandP(0, CCA_NEW_AI
| company_id
<< 16, 0, CMD_COMPANY_CTRL
);
1222 IConsolePrint(CC_DEFAULT
, "AI reloaded.");
1227 DEF_CONSOLE_CMD(ConStopAI
)
1230 IConsoleHelp("Stop an AI. Usage: 'stop_ai <company-id>'");
1231 IConsoleHelp("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.");
1235 if (_game_mode
!= GM_NORMAL
) {
1236 IConsoleWarning("AIs can only be managed in a game.");
1240 if (_networking
&& !_network_server
) {
1241 IConsoleWarning("Only the server can stop an AI.");
1245 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1246 if (!Company::IsValidID(company_id
)) {
1247 IConsolePrintF(CC_DEFAULT
, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES
);
1251 if (Company::IsHumanID(company_id
) || company_id
== _local_company
) {
1252 IConsoleWarning("Company is not controlled by an AI.");
1256 /* Now kill the company of the AI. */
1257 DoCommandP(0, CCA_DELETE
| company_id
<< 16 | CRR_MANUAL
<< 24, 0, CMD_COMPANY_CTRL
);
1258 IConsolePrint(CC_DEFAULT
, "AI stopped, company deleted.");
1263 DEF_CONSOLE_CMD(ConRescanAI
)
1266 IConsoleHelp("Rescan the AI dir for scripts. Usage: 'rescan_ai'");
1270 if (_networking
&& !_network_server
) {
1271 IConsoleWarning("Only the server can rescan the AI dir for scripts.");
1280 DEF_CONSOLE_CMD(ConRescanGame
)
1283 IConsoleHelp("Rescan the Game Script dir for scripts. Usage: 'rescan_game'");
1287 if (_networking
&& !_network_server
) {
1288 IConsoleWarning("Only the server can rescan the Game Script dir for scripts.");
1297 DEF_CONSOLE_CMD(ConRescanNewGRF
)
1300 IConsoleHelp("Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'");
1304 ScanNewGRFFiles(nullptr);
1309 DEF_CONSOLE_CMD(ConGetSeed
)
1312 IConsoleHelp("Returns the seed used to create this game. Usage: 'getseed'");
1313 IConsoleHelp("The seed can be used to reproduce the exact same map as the game started with.");
1317 IConsolePrintF(CC_DEFAULT
, "Generation Seed: %u", _settings_game
.game_creation
.generation_seed
);
1321 DEF_CONSOLE_CMD(ConGetDate
)
1324 IConsoleHelp("Returns the current date (year-month-day) of the game. Usage: 'getdate'");
1329 ConvertDateToYMD(_date
, &ymd
);
1330 IConsolePrintF(CC_DEFAULT
, "Date: %04d-%02d-%02d", ymd
.year
, ymd
.month
+ 1, ymd
.day
);
1334 DEF_CONSOLE_CMD(ConGetSysDate
)
1337 IConsoleHelp("Returns the current date (year-month-day) of your system. Usage: 'getsysdate'");
1343 auto timeinfo
= localtime(&t
);
1344 IConsolePrintF(CC_DEFAULT
, "System Date: %04d-%02d-%02d %02d:%02d:%02d", timeinfo
->tm_year
+ 1900, timeinfo
->tm_mon
+ 1, timeinfo
->tm_mday
, timeinfo
->tm_hour
, timeinfo
->tm_min
, timeinfo
->tm_sec
);
1349 DEF_CONSOLE_CMD(ConAlias
)
1351 IConsoleAlias
*alias
;
1354 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1358 if (argc
< 3) return false;
1360 alias
= IConsoleAliasGet(argv
[1]);
1361 if (alias
== nullptr) {
1362 IConsoleAliasRegister(argv
[1], argv
[2]);
1364 free(alias
->cmdline
);
1365 alias
->cmdline
= stredup(argv
[2]);
1370 DEF_CONSOLE_CMD(ConScreenShot
)
1373 IConsoleHelp("Create a screenshot of the game. Usage: 'screenshot [big | giant | no_con | minimap] [file name]'");
1374 IConsoleHelp("'big' makes a zoomed-in screenshot of the visible area, 'giant' makes a screenshot of the "
1375 "whole map, 'no_con' hides the console to create the screenshot. 'big' or 'giant' "
1376 "screenshots are always drawn without console. "
1377 "'minimap' makes a top-viewed minimap screenshot of whole world which represents one tile by one pixel.");
1381 if (argc
> 3) return false;
1383 ScreenshotType type
= SC_VIEWPORT
;
1384 const char *name
= nullptr;
1387 if (strcmp(argv
[1], "big") == 0) {
1388 /* screenshot big [filename] */
1390 if (argc
> 2) name
= argv
[2];
1391 } else if (strcmp(argv
[1], "giant") == 0) {
1392 /* screenshot giant [filename] */
1394 if (argc
> 2) name
= argv
[2];
1395 } else if (strcmp(argv
[1], "minimap") == 0) {
1396 /* screenshot minimap [filename] */
1398 if (argc
> 2) name
= argv
[2];
1399 } else if (strcmp(argv
[1], "no_con") == 0) {
1400 /* screenshot no_con [filename] */
1402 if (argc
> 2) name
= argv
[2];
1403 } else if (argc
== 2) {
1404 /* screenshot filename */
1407 /* screenshot argv[1] argv[2] - invalid */
1412 MakeScreenshot(type
, name
);
1416 DEF_CONSOLE_CMD(ConInfoCmd
)
1419 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1423 if (argc
< 2) return false;
1425 const IConsoleCmd
*cmd
= IConsoleCmdGet(argv
[1]);
1426 if (cmd
== nullptr) {
1427 IConsoleError("the given command was not found");
1431 IConsolePrintF(CC_DEFAULT
, "command name: %s", cmd
->name
);
1432 IConsolePrintF(CC_DEFAULT
, "command proc: %p", cmd
->proc
);
1434 if (cmd
->hook
!= nullptr) IConsoleWarning("command is hooked");
1439 DEF_CONSOLE_CMD(ConDebugLevel
)
1442 IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
1443 IConsoleHelp("Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'s");
1447 if (argc
> 2) return false;
1450 IConsolePrintF(CC_DEFAULT
, "Current debug-level: '%s'", GetDebugString());
1452 SetDebugString(argv
[1]);
1458 DEF_CONSOLE_CMD(ConExit
)
1461 IConsoleHelp("Exit the game. Usage: 'exit'");
1465 if (_game_mode
== GM_NORMAL
&& _settings_client
.gui
.autosave_on_exit
) DoExitSave();
1471 DEF_CONSOLE_CMD(ConPart
)
1474 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1478 if (_game_mode
!= GM_NORMAL
) return false;
1480 _switch_mode
= SM_MENU
;
1484 DEF_CONSOLE_CMD(ConHelp
)
1487 const IConsoleCmd
*cmd
;
1488 const IConsoleAlias
*alias
;
1490 RemoveUnderscores(argv
[1]);
1491 cmd
= IConsoleCmdGet(argv
[1]);
1492 if (cmd
!= nullptr) {
1493 cmd
->proc(0, nullptr);
1497 alias
= IConsoleAliasGet(argv
[1]);
1498 if (alias
!= nullptr) {
1499 cmd
= IConsoleCmdGet(alias
->cmdline
);
1500 if (cmd
!= nullptr) {
1501 cmd
->proc(0, nullptr);
1504 IConsolePrintF(CC_ERROR
, "ERROR: alias is of special type, please see its execution-line: '%s'", alias
->cmdline
);
1508 IConsoleError("command not found");
1512 IConsolePrint(CC_WARNING
, " ---- OpenTTD Console Help ---- ");
1513 IConsolePrint(CC_DEFAULT
, " - commands: [command to list all commands: list_cmds]");
1514 IConsolePrint(CC_DEFAULT
, " call commands with '<command> <arg2> <arg3>...'");
1515 IConsolePrint(CC_DEFAULT
, " - to assign strings, or use them as arguments, enclose it within quotes");
1516 IConsolePrint(CC_DEFAULT
, " like this: '<command> \"string argument with spaces\"'");
1517 IConsolePrint(CC_DEFAULT
, " - use 'help <command>' to get specific information");
1518 IConsolePrint(CC_DEFAULT
, " - scroll console output with shift + (up | down | pageup | pagedown)");
1519 IConsolePrint(CC_DEFAULT
, " - scroll console input history with the up or down arrows");
1520 IConsolePrint(CC_DEFAULT
, "");
1524 DEF_CONSOLE_CMD(ConListCommands
)
1527 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1531 for (const IConsoleCmd
*cmd
= _iconsole_cmds
; cmd
!= nullptr; cmd
= cmd
->next
) {
1532 if (argv
[1] == nullptr || strstr(cmd
->name
, argv
[1]) != nullptr) {
1533 if (cmd
->hook
== nullptr || cmd
->hook(false) != CHR_HIDE
) IConsolePrintF(CC_DEFAULT
, "%s", cmd
->name
);
1540 DEF_CONSOLE_CMD(ConListAliases
)
1543 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1547 for (const IConsoleAlias
*alias
= _iconsole_aliases
; alias
!= nullptr; alias
= alias
->next
) {
1548 if (argv
[1] == nullptr || strstr(alias
->name
, argv
[1]) != nullptr) {
1549 IConsolePrintF(CC_DEFAULT
, "%s => %s", alias
->name
, alias
->cmdline
);
1556 DEF_CONSOLE_CMD(ConCompanies
)
1559 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1563 for (const Company
*c
: Company::Iterate()) {
1564 /* Grab the company name */
1565 char company_name
[512];
1566 SetDParam(0, c
->index
);
1567 GetString(company_name
, STR_COMPANY_NAME
, lastof(company_name
));
1569 const char *password_state
= "";
1571 password_state
= "AI";
1572 } else if (_network_server
) {
1573 password_state
= StrEmpty(_network_company_states
[c
->index
].password
) ? "unprotected" : "protected";
1577 GetString(colour
, STR_COLOUR_DARK_BLUE
+ _company_colours
[c
->index
], lastof(colour
));
1578 IConsolePrintF(CC_INFO
, "#:%d(%s) Company Name: '%s' Year Founded: %d Money: " OTTD_PRINTF64
" Loan: " OTTD_PRINTF64
" Value: " OTTD_PRINTF64
" (T:%d, R:%d, P:%d, S:%d) %s",
1579 c
->index
+ 1, colour
, company_name
,
1580 c
->inaugurated_year
, (int64
)c
->money
, (int64
)c
->current_loan
, (int64
)CalculateCompanyValue(c
),
1581 c
->group_all
[VEH_TRAIN
].num_vehicle
,
1582 c
->group_all
[VEH_ROAD
].num_vehicle
,
1583 c
->group_all
[VEH_AIRCRAFT
].num_vehicle
,
1584 c
->group_all
[VEH_SHIP
].num_vehicle
,
1591 DEF_CONSOLE_CMD(ConSay
)
1594 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1598 if (argc
!= 2) return false;
1600 if (!_network_server
) {
1601 NetworkClientSendChat(NETWORK_ACTION_CHAT
, DESTTYPE_BROADCAST
, 0 /* param does not matter */, argv
[1]);
1603 bool from_admin
= (_redirect_console_to_admin
< INVALID_ADMIN_ID
);
1604 NetworkServerSendChat(NETWORK_ACTION_CHAT
, DESTTYPE_BROADCAST
, 0, argv
[1], CLIENT_ID_SERVER
, from_admin
);
1610 DEF_CONSOLE_CMD(ConSayCompany
)
1613 IConsoleHelp("Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'");
1614 IConsoleHelp("CompanyNo is the company that plays as company <companyno>, 1 through max_companies");
1618 if (argc
!= 3) return false;
1620 CompanyID company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1621 if (!Company::IsValidID(company_id
)) {
1622 IConsolePrintF(CC_DEFAULT
, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES
);
1626 if (!_network_server
) {
1627 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY
, DESTTYPE_TEAM
, company_id
, argv
[2]);
1629 bool from_admin
= (_redirect_console_to_admin
< INVALID_ADMIN_ID
);
1630 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY
, DESTTYPE_TEAM
, company_id
, argv
[2], CLIENT_ID_SERVER
, from_admin
);
1636 DEF_CONSOLE_CMD(ConSayClient
)
1639 IConsoleHelp("Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'");
1640 IConsoleHelp("For client-id's, see the command 'clients'");
1644 if (argc
!= 3) return false;
1646 if (!_network_server
) {
1647 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT
, DESTTYPE_CLIENT
, atoi(argv
[1]), argv
[2]);
1649 bool from_admin
= (_redirect_console_to_admin
< INVALID_ADMIN_ID
);
1650 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT
, DESTTYPE_CLIENT
, atoi(argv
[1]), argv
[2], CLIENT_ID_SERVER
, from_admin
);
1656 DEF_CONSOLE_CMD(ConCompanyPassword
)
1659 const char *helpmsg
;
1661 if (_network_dedicated
) {
1662 helpmsg
= "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\"";
1663 } else if (_network_server
) {
1664 helpmsg
= "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'";
1666 helpmsg
= "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1669 IConsoleHelp(helpmsg
);
1670 IConsoleHelp("Use \"*\" to disable the password.");
1674 CompanyID company_id
;
1675 const char *password
;
1676 const char *errormsg
;
1679 company_id
= _local_company
;
1681 errormsg
= "You have to own a company to make use of this command.";
1682 } else if (argc
== 3 && _network_server
) {
1683 company_id
= (CompanyID
)(atoi(argv
[1]) - 1);
1685 errormsg
= "You have to specify the ID of a valid human controlled company.";
1690 if (!Company::IsValidHumanID(company_id
)) {
1691 IConsoleError(errormsg
);
1695 password
= NetworkChangeCompanyPassword(company_id
, password
);
1697 if (StrEmpty(password
)) {
1698 IConsolePrintF(CC_WARNING
, "Company password cleared");
1700 IConsolePrintF(CC_WARNING
, "Company password changed to: %s", password
);
1706 /* Content downloading only is available with ZLIB */
1707 #if defined(WITH_ZLIB)
1708 #include "network/network_content.h"
1710 /** Resolve a string to a content type. */
1711 static ContentType
StringToContentType(const char *str
)
1713 static const char * const inv_lookup
[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1714 for (uint i
= 1 /* there is no type 0 */; i
< lengthof(inv_lookup
); i
++) {
1715 if (strcasecmp(str
, inv_lookup
[i
]) == 0) return (ContentType
)i
;
1717 return CONTENT_TYPE_END
;
1720 /** Asynchronous callback */
1721 struct ConsoleContentCallback
: public ContentCallback
{
1722 void OnConnect(bool success
)
1724 IConsolePrintF(CC_DEFAULT
, "Content server connection %s", success
? "established" : "failed");
1729 IConsolePrintF(CC_DEFAULT
, "Content server connection closed");
1732 void OnDownloadComplete(ContentID cid
)
1734 IConsolePrintF(CC_DEFAULT
, "Completed download of %d", cid
);
1739 * Outputs content state information to console
1740 * @param ci the content info
1742 static void OutputContentState(const ContentInfo
*const ci
)
1744 static const char * const types
[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1745 assert_compile(lengthof(types
) == CONTENT_TYPE_END
- CONTENT_TYPE_BEGIN
);
1746 static const char * const states
[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1747 static const TextColour state_to_colour
[] = { CC_COMMAND
, CC_INFO
, CC_INFO
, CC_WHITE
, CC_ERROR
};
1749 char buf
[sizeof(ci
->md5sum
) * 2 + 1];
1750 md5sumToString(buf
, lastof(buf
), ci
->md5sum
);
1751 IConsolePrintF(state_to_colour
[ci
->state
], "%d, %s, %s, %s, %08X, %s", ci
->id
, types
[ci
->type
- 1], states
[ci
->state
], ci
->name
, ci
->unique_id
, buf
);
1754 DEF_CONSOLE_CMD(ConContent
)
1756 static ContentCallback
*cb
= nullptr;
1757 if (cb
== nullptr) {
1758 cb
= new ConsoleContentCallback();
1759 _network_content_client
.AddCallback(cb
);
1763 IConsoleHelp("Query, select and download content. Usage: 'content update|upgrade|select [all|id]|unselect [all|id]|state [filter]|download'");
1764 IConsoleHelp(" update: get a new list of downloadable content; must be run first");
1765 IConsoleHelp(" upgrade: select all items that are upgrades");
1766 IConsoleHelp(" select: select a specific item given by its id or 'all' to select all. If no parameter is given, all selected content will be listed");
1767 IConsoleHelp(" unselect: unselect a specific item given by its id or 'all' to unselect all");
1768 IConsoleHelp(" state: show the download/select state of all downloadable content. Optionally give a filter string");
1769 IConsoleHelp(" download: download all content you've selected");
1773 if (strcasecmp(argv
[1], "update") == 0) {
1774 _network_content_client
.RequestContentList((argc
> 2) ? StringToContentType(argv
[2]) : CONTENT_TYPE_END
);
1778 if (strcasecmp(argv
[1], "upgrade") == 0) {
1779 _network_content_client
.SelectUpgrade();
1783 if (strcasecmp(argv
[1], "select") == 0) {
1785 /* List selected content */
1786 IConsolePrintF(CC_WHITE
, "id, type, state, name");
1787 for (ConstContentIterator iter
= _network_content_client
.Begin(); iter
!= _network_content_client
.End(); iter
++) {
1788 if ((*iter
)->state
!= ContentInfo::SELECTED
&& (*iter
)->state
!= ContentInfo::AUTOSELECTED
) continue;
1789 OutputContentState(*iter
);
1791 } else if (strcasecmp(argv
[2], "all") == 0) {
1792 _network_content_client
.SelectAll();
1794 _network_content_client
.Select((ContentID
)atoi(argv
[2]));
1799 if (strcasecmp(argv
[1], "unselect") == 0) {
1801 IConsoleError("You must enter the id.");
1804 if (strcasecmp(argv
[2], "all") == 0) {
1805 _network_content_client
.UnselectAll();
1807 _network_content_client
.Unselect((ContentID
)atoi(argv
[2]));
1812 if (strcasecmp(argv
[1], "state") == 0) {
1813 IConsolePrintF(CC_WHITE
, "id, type, state, name");
1814 for (ConstContentIterator iter
= _network_content_client
.Begin(); iter
!= _network_content_client
.End(); iter
++) {
1815 if (argc
> 2 && strcasestr((*iter
)->name
, argv
[2]) == nullptr) continue;
1816 OutputContentState(*iter
);
1821 if (strcasecmp(argv
[1], "download") == 0) {
1824 _network_content_client
.DownloadSelectedContent(files
, bytes
);
1825 IConsolePrintF(CC_DEFAULT
, "Downloading %d file(s) (%d bytes)", files
, bytes
);
1831 #endif /* defined(WITH_ZLIB) */
1833 DEF_CONSOLE_CMD(ConSetting
)
1836 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1837 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1841 if (argc
== 1 || argc
> 3) return false;
1844 IConsoleGetSetting(argv
[1]);
1846 IConsoleSetSetting(argv
[1], argv
[2]);
1852 DEF_CONSOLE_CMD(ConSettingNewgame
)
1855 IConsoleHelp("Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'");
1856 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1860 if (argc
== 1 || argc
> 3) return false;
1863 IConsoleGetSetting(argv
[1], true);
1865 IConsoleSetSetting(argv
[1], argv
[2], true);
1871 DEF_CONSOLE_CMD(ConListSettings
)
1874 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1878 if (argc
> 2) return false;
1880 IConsoleListSettings((argc
== 2) ? argv
[1] : nullptr);
1884 DEF_CONSOLE_CMD(ConGamelogPrint
)
1886 GamelogPrintConsole();
1890 DEF_CONSOLE_CMD(ConNewGRFReload
)
1893 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1901 DEF_CONSOLE_CMD(ConNewGRFProfile
)
1904 IConsoleHelp("Collect performance data about NewGRF sprite requests and callbacks. Sub-commands can be abbreviated.");
1905 IConsoleHelp("Usage: newgrf_profile [list]");
1906 IConsoleHelp(" List all NewGRFs that can be profiled, and their status.");
1907 IConsoleHelp("Usage: newgrf_profile select <grf-num>...");
1908 IConsoleHelp(" Select one or more GRFs for profiling.");
1909 IConsoleHelp("Usage: newgrf_profile unselect <grf-num>...");
1910 IConsoleHelp(" 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.");
1911 IConsoleHelp("Usage: newgrf_profile start [<num-days>]");
1912 IConsoleHelp(" Begin profiling all selected GRFs. If a number of days is provided, profiling stops after that many in-game days.");
1913 IConsoleHelp("Usage: newgrf_profile stop");
1914 IConsoleHelp(" End profiling and write the collected data to CSV files.");
1915 IConsoleHelp("Usage: newgrf_profile abort");
1916 IConsoleHelp(" End profiling and discard all collected data.");
1920 extern const std::vector
<GRFFile
*> &GetAllGRFFiles();
1921 const std::vector
<GRFFile
*> &files
= GetAllGRFFiles();
1923 /* "list" sub-command */
1924 if (argc
== 1 || strncasecmp(argv
[1], "lis", 3) == 0) {
1925 IConsolePrint(CC_INFO
, "Loaded GRF files:");
1927 for (GRFFile
*grf
: files
) {
1928 auto profiler
= std::find_if(_newgrf_profilers
.begin(), _newgrf_profilers
.end(), [&](NewGRFProfiler
&pr
) { return pr
.grffile
== grf
; });
1929 bool selected
= profiler
!= _newgrf_profilers
.end();
1930 bool active
= selected
&& profiler
->active
;
1931 TextColour tc
= active
? TC_LIGHT_BLUE
: selected
? TC_GREEN
: CC_INFO
;
1932 const char *statustext
= active
? " (active)" : selected
? " (selected)" : "";
1933 IConsolePrintF(tc
, "%d: [%08X] %s%s", i
, BSWAP32(grf
->grfid
), grf
->filename
, statustext
);
1939 /* "select" sub-command */
1940 if (strncasecmp(argv
[1], "sel", 3) == 0 && argc
>= 3) {
1941 for (size_t argnum
= 2; argnum
< argc
; ++argnum
) {
1942 int grfnum
= atoi(argv
[argnum
]);
1943 if (grfnum
< 1 || grfnum
> (int)files
.size()) { // safe cast, files.size() should not be larger than a few hundred in the most extreme cases
1944 IConsolePrintF(CC_WARNING
, "GRF number %d out of range, not added.", grfnum
);
1947 GRFFile
*grf
= files
[grfnum
- 1];
1948 if (std::any_of(_newgrf_profilers
.begin(), _newgrf_profilers
.end(), [&](NewGRFProfiler
&pr
) { return pr
.grffile
== grf
; })) {
1949 IConsolePrintF(CC_WARNING
, "GRF number %d [%08X] is already selected for profiling.", grfnum
, BSWAP32(grf
->grfid
));
1952 _newgrf_profilers
.emplace_back(grf
);
1957 /* "unselect" sub-command */
1958 if (strncasecmp(argv
[1], "uns", 3) == 0 && argc
>= 3) {
1959 for (size_t argnum
= 2; argnum
< argc
; ++argnum
) {
1960 if (strcasecmp(argv
[argnum
], "all") == 0) {
1961 _newgrf_profilers
.clear();
1964 int grfnum
= atoi(argv
[argnum
]);
1965 if (grfnum
< 1 || grfnum
> (int)files
.size()) {
1966 IConsolePrintF(CC_WARNING
, "GRF number %d out of range, not removing.", grfnum
);
1969 GRFFile
*grf
= files
[grfnum
- 1];
1970 auto pos
= std::find_if(_newgrf_profilers
.begin(), _newgrf_profilers
.end(), [&](NewGRFProfiler
&pr
) { return pr
.grffile
== grf
; });
1971 if (pos
!= _newgrf_profilers
.end()) _newgrf_profilers
.erase(pos
);
1976 /* "start" sub-command */
1977 if (strncasecmp(argv
[1], "sta", 3) == 0) {
1980 for (NewGRFProfiler
&pr
: _newgrf_profilers
) {
1985 if (!grfids
.empty()) grfids
+= ", ";
1986 char grfidstr
[12]{ 0 };
1987 seprintf(grfidstr
, lastof(grfidstr
), "[%08X]", BSWAP32(pr
.grffile
->grfid
));
1992 IConsolePrintF(CC_DEBUG
, "Started profiling for GRFID%s %s", (started
> 1) ? "s" : "", grfids
.c_str());
1994 int days
= max(atoi(argv
[2]), 1);
1995 _newgrf_profile_end_date
= _date
+ days
;
1997 char datestrbuf
[32]{ 0 };
1998 SetDParam(0, _newgrf_profile_end_date
);
1999 GetString(datestrbuf
, STR_JUST_DATE_ISO
, lastof(datestrbuf
));
2000 IConsolePrintF(CC_DEBUG
, "Profiling will automatically stop on game date %s", datestrbuf
);
2002 _newgrf_profile_end_date
= MAX_DAY
;
2004 } else if (_newgrf_profilers
.empty()) {
2005 IConsolePrintF(CC_WARNING
, "No GRFs selected for profiling, did not start.");
2007 IConsolePrintF(CC_WARNING
, "Did not start profiling for any GRFs, all selected GRFs are already profiling.");
2012 /* "stop" sub-command */
2013 if (strncasecmp(argv
[1], "sto", 3) == 0) {
2014 NewGRFProfiler::FinishAll();
2018 /* "abort" sub-command */
2019 if (strncasecmp(argv
[1], "abo", 3) == 0) {
2020 for (NewGRFProfiler
&pr
: _newgrf_profilers
) {
2023 _newgrf_profile_end_date
= MAX_DAY
;
2035 static void IConsoleDebugLibRegister()
2037 IConsoleCmdRegister("resettile", ConResetTile
);
2038 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
2039 IConsoleAliasRegister("dbg_echo2", "echo %!");
2043 DEF_CONSOLE_CMD(ConFramerate
)
2045 extern void ConPrintFramerate(); // framerate_gui.cpp
2048 IConsoleHelp("Show frame rate and game speed information");
2052 ConPrintFramerate();
2056 DEF_CONSOLE_CMD(ConFramerateWindow
)
2058 extern void ShowFramerateWindow();
2061 IConsoleHelp("Open the frame rate window");
2065 if (_network_dedicated
) {
2066 IConsoleError("Can not open frame rate window on a dedicated server");
2070 ShowFramerateWindow();
2074 /*******************************
2075 * console command registration
2076 *******************************/
2078 void IConsoleStdLibRegister()
2080 IConsoleCmdRegister("debug_level", ConDebugLevel
);
2081 IConsoleCmdRegister("echo", ConEcho
);
2082 IConsoleCmdRegister("echoc", ConEchoC
);
2083 IConsoleCmdRegister("exec", ConExec
);
2084 IConsoleCmdRegister("exit", ConExit
);
2085 IConsoleCmdRegister("part", ConPart
);
2086 IConsoleCmdRegister("help", ConHelp
);
2087 IConsoleCmdRegister("info_cmd", ConInfoCmd
);
2088 IConsoleCmdRegister("list_cmds", ConListCommands
);
2089 IConsoleCmdRegister("list_aliases", ConListAliases
);
2090 IConsoleCmdRegister("newgame", ConNewGame
);
2091 IConsoleCmdRegister("restart", ConRestart
);
2092 IConsoleCmdRegister("getseed", ConGetSeed
);
2093 IConsoleCmdRegister("getdate", ConGetDate
);
2094 IConsoleCmdRegister("getsysdate", ConGetSysDate
);
2095 IConsoleCmdRegister("quit", ConExit
);
2096 IConsoleCmdRegister("resetengines", ConResetEngines
, ConHookNoNetwork
);
2097 IConsoleCmdRegister("reset_enginepool", ConResetEnginePool
, ConHookNoNetwork
);
2098 IConsoleCmdRegister("return", ConReturn
);
2099 IConsoleCmdRegister("screenshot", ConScreenShot
);
2100 IConsoleCmdRegister("script", ConScript
);
2101 IConsoleCmdRegister("scrollto", ConScrollToTile
);
2102 IConsoleCmdRegister("alias", ConAlias
);
2103 IConsoleCmdRegister("load", ConLoad
);
2104 IConsoleCmdRegister("rm", ConRemove
);
2105 IConsoleCmdRegister("save", ConSave
);
2106 IConsoleCmdRegister("saveconfig", ConSaveConfig
);
2107 IConsoleCmdRegister("ls", ConListFiles
);
2108 IConsoleCmdRegister("cd", ConChangeDirectory
);
2109 IConsoleCmdRegister("pwd", ConPrintWorkingDirectory
);
2110 IConsoleCmdRegister("clear", ConClearBuffer
);
2111 IConsoleCmdRegister("setting", ConSetting
);
2112 IConsoleCmdRegister("setting_newgame", ConSettingNewgame
);
2113 IConsoleCmdRegister("list_settings",ConListSettings
);
2114 IConsoleCmdRegister("gamelog", ConGamelogPrint
);
2115 IConsoleCmdRegister("rescan_newgrf", ConRescanNewGRF
);
2117 IConsoleAliasRegister("dir", "ls");
2118 IConsoleAliasRegister("del", "rm %+");
2119 IConsoleAliasRegister("newmap", "newgame");
2120 IConsoleAliasRegister("patch", "setting %+");
2121 IConsoleAliasRegister("set", "setting %+");
2122 IConsoleAliasRegister("set_newgame", "setting_newgame %+");
2123 IConsoleAliasRegister("list_patches", "list_settings %+");
2124 IConsoleAliasRegister("developer", "setting developer %+");
2126 IConsoleCmdRegister("list_ai_libs", ConListAILibs
);
2127 IConsoleCmdRegister("list_ai", ConListAI
);
2128 IConsoleCmdRegister("reload_ai", ConReloadAI
);
2129 IConsoleCmdRegister("rescan_ai", ConRescanAI
);
2130 IConsoleCmdRegister("start_ai", ConStartAI
);
2131 IConsoleCmdRegister("stop_ai", ConStopAI
);
2133 IConsoleCmdRegister("list_game", ConListGame
);
2134 IConsoleCmdRegister("list_game_libs", ConListGameLibs
);
2135 IConsoleCmdRegister("rescan_game", ConRescanGame
);
2137 IConsoleCmdRegister("companies", ConCompanies
);
2138 IConsoleAliasRegister("players", "companies");
2140 /* networking functions */
2142 /* Content downloading is only available with ZLIB */
2143 #if defined(WITH_ZLIB)
2144 IConsoleCmdRegister("content", ConContent
);
2145 #endif /* defined(WITH_ZLIB) */
2147 /*** Networking commands ***/
2148 IConsoleCmdRegister("say", ConSay
, ConHookNeedNetwork
);
2149 IConsoleCmdRegister("say_company", ConSayCompany
, ConHookNeedNetwork
);
2150 IConsoleAliasRegister("say_player", "say_company %+");
2151 IConsoleCmdRegister("say_client", ConSayClient
, ConHookNeedNetwork
);
2153 IConsoleCmdRegister("connect", ConNetworkConnect
, ConHookClientOnly
);
2154 IConsoleCmdRegister("clients", ConNetworkClients
, ConHookNeedNetwork
);
2155 IConsoleCmdRegister("status", ConStatus
, ConHookServerOnly
);
2156 IConsoleCmdRegister("server_info", ConServerInfo
, ConHookServerOnly
);
2157 IConsoleAliasRegister("info", "server_info");
2158 IConsoleCmdRegister("reconnect", ConNetworkReconnect
, ConHookClientOnly
);
2159 IConsoleCmdRegister("rcon", ConRcon
, ConHookNeedNetwork
);
2161 IConsoleCmdRegister("join", ConJoinCompany
, ConHookNeedNetwork
);
2162 IConsoleAliasRegister("spectate", "join 255");
2163 IConsoleCmdRegister("move", ConMoveClient
, ConHookServerOnly
);
2164 IConsoleCmdRegister("reset_company", ConResetCompany
, ConHookServerOnly
);
2165 IConsoleAliasRegister("clean_company", "reset_company %A");
2166 IConsoleCmdRegister("client_name", ConClientNickChange
, ConHookServerOnly
);
2167 IConsoleCmdRegister("kick", ConKick
, ConHookServerOnly
);
2168 IConsoleCmdRegister("ban", ConBan
, ConHookServerOnly
);
2169 IConsoleCmdRegister("unban", ConUnBan
, ConHookServerOnly
);
2170 IConsoleCmdRegister("banlist", ConBanList
, ConHookServerOnly
);
2172 IConsoleCmdRegister("pause", ConPauseGame
, ConHookServerOnly
);
2173 IConsoleCmdRegister("unpause", ConUnpauseGame
, ConHookServerOnly
);
2175 IConsoleCmdRegister("company_pw", ConCompanyPassword
, ConHookNeedNetwork
);
2176 IConsoleAliasRegister("company_password", "company_pw %+");
2178 IConsoleAliasRegister("net_frame_freq", "setting frame_freq %+");
2179 IConsoleAliasRegister("net_sync_freq", "setting sync_freq %+");
2180 IConsoleAliasRegister("server_pw", "setting server_password %+");
2181 IConsoleAliasRegister("server_password", "setting server_password %+");
2182 IConsoleAliasRegister("rcon_pw", "setting rcon_password %+");
2183 IConsoleAliasRegister("rcon_password", "setting rcon_password %+");
2184 IConsoleAliasRegister("name", "setting client_name %+");
2185 IConsoleAliasRegister("server_name", "setting server_name %+");
2186 IConsoleAliasRegister("server_port", "setting server_port %+");
2187 IConsoleAliasRegister("server_advertise", "setting server_advertise %+");
2188 IConsoleAliasRegister("max_clients", "setting max_clients %+");
2189 IConsoleAliasRegister("max_companies", "setting max_companies %+");
2190 IConsoleAliasRegister("max_spectators", "setting max_spectators %+");
2191 IConsoleAliasRegister("max_join_time", "setting max_join_time %+");
2192 IConsoleAliasRegister("pause_on_join", "setting pause_on_join %+");
2193 IConsoleAliasRegister("autoclean_companies", "setting autoclean_companies %+");
2194 IConsoleAliasRegister("autoclean_protected", "setting autoclean_protected %+");
2195 IConsoleAliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2196 IConsoleAliasRegister("restart_game_year", "setting restart_game_year %+");
2197 IConsoleAliasRegister("min_players", "setting min_active_clients %+");
2198 IConsoleAliasRegister("reload_cfg", "setting reload_cfg %+");
2200 /* debugging stuff */
2202 IConsoleDebugLibRegister();
2204 IConsoleCmdRegister("fps", ConFramerate
);
2205 IConsoleCmdRegister("fps_wnd", ConFramerateWindow
);
2207 /* NewGRF development stuff */
2208 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload
, ConHookNewGRFDeveloperTool
);
2209 IConsoleCmdRegister("newgrf_profile", ConNewGRFProfile
, ConHookNewGRFDeveloperTool
);