Update readme and changelog for v1.27.0
[openttd-joker.git] / src / console_cmds.cpp
blob516ffe94a6f5812e941676c5282bf1496f5a29e2
1 /* $Id: console_cmds.cpp 26000 2013-11-14 22:50:16Z zuu $ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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 */
10 /** @file console_cmds.cpp Implementation of the console hooks. */
12 #include "stdafx.h"
13 #include "console_internal.h"
14 #include "debug.h"
15 #include "engine_func.h"
16 #include "landscape.h"
17 #include "saveload/saveload.h"
18 #include "network/network.h"
19 #include "network/network_func.h"
20 #include "network/network_base.h"
21 #include "network/network_admin.h"
22 #include "network/network_client.h"
23 #include "command_func.h"
24 #include "settings_func.h"
25 #include "fios.h"
26 #include "fileio_func.h"
27 #include "screenshot.h"
28 #include "genworld.h"
29 #include "strings_func.h"
30 #include "viewport_func.h"
31 #include "window_func.h"
32 #include "date_func.h"
33 #include "company_func.h"
34 #include "gamelog.h"
35 #include "ai/ai.hpp"
36 #include "ai/ai_config.hpp"
37 #include "newgrf.h"
38 #include "console_func.h"
39 #include "engine_base.h"
40 #include "game/game.hpp"
41 #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 {
50 public:
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()
59 this->Clear();
60 this->file_list_valid = false;
63 /**
64 * (Re-)validate the file storage cache. Only makes a change if the storage was invalid, or if \a force_reload.
65 * @param 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)
85 /****************
86 * command hooks
87 ****************/
89 #ifdef ENABLE_NETWORK
91 /**
92 * Check network availability and inform in console about failure of detection.
93 * @return Network availability.
95 static inline bool NetworkAvailable(bool echo)
97 if (!_network_available) {
98 if (echo) IConsoleError("You cannot use this command because there is no network available.");
99 return false;
101 return true;
105 * Check whether we are a server.
106 * @return Are we a server? True when yes, false otherwise.
108 DEF_CONSOLE_HOOK(ConHookServerOnly)
110 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
112 if (!_network_server) {
113 if (echo) IConsoleError("This command is only available to a network server.");
114 return CHR_DISALLOW;
116 return CHR_ALLOW;
120 * Check whether we are a client in a network game.
121 * @return Are we a client in a network game? True when yes, false otherwise.
123 DEF_CONSOLE_HOOK(ConHookClientOnly)
125 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
127 if (_network_server) {
128 if (echo) IConsoleError("This command is not available to a network server.");
129 return CHR_DISALLOW;
131 return CHR_ALLOW;
135 * Check whether we are in a multiplayer game.
136 * @return True when we are client or server in a network game.
138 DEF_CONSOLE_HOOK(ConHookNeedNetwork)
140 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
142 if (!_networking || (!_network_server && !MyClient::IsConnected())) {
143 if (echo) IConsoleError("Not connected. This command is only available in multiplayer.");
144 return CHR_DISALLOW;
146 return CHR_ALLOW;
150 * Check whether we are in single player mode.
151 * @return True when no network is active.
153 DEF_CONSOLE_HOOK(ConHookNoNetwork)
155 if (_networking) {
156 if (echo) IConsoleError("This command is forbidden in multiplayer.");
157 return CHR_DISALLOW;
159 return CHR_ALLOW;
162 #else
163 # define ConHookNoNetwork nullptr
164 #endif /* ENABLE_NETWORK */
166 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool)
168 if (_settings_client.gui.newgrf_developer_tools) {
169 if (_game_mode == GM_MENU) {
170 if (echo) IConsoleError("This command is only available in game and editor.");
171 return CHR_DISALLOW;
173 #ifdef ENABLE_NETWORK
174 return ConHookNoNetwork(echo);
175 #else
176 return CHR_ALLOW;
177 #endif
179 return CHR_HIDE;
183 * Show help for the console.
184 * @param str String to print in the console.
186 static void IConsoleHelp(const char *str)
188 IConsolePrintF(CC_WARNING, "- %s", str);
192 * Reset status of all engines.
193 * @return Will always succeed.
195 DEF_CONSOLE_CMD(ConResetEngines)
197 if (argc == 0) {
198 IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'");
199 return true;
202 StartupEngines();
203 return true;
207 * Reset status of the engine pool.
208 * @return Will always return true.
209 * @note Resetting the pool only succeeds when there are no vehicles ingame.
211 DEF_CONSOLE_CMD(ConResetEnginePool)
213 if (argc == 0) {
214 IConsoleHelp("Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
215 return true;
218 if (_game_mode == GM_MENU) {
219 IConsoleError("This command is only available in game and editor.");
220 return true;
223 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
224 IConsoleError("This can only be done when there are no vehicles in the game.");
225 return true;
228 return true;
231 DEF_CONSOLE_CMD(ConCheckCaches)
233 if (argc == 0) {
234 IConsoleHelp("Debug: Check caches");
235 return true;
238 if (argc > 2) return false;
240 bool broadcast = (argc == 2 && atoi(argv[1]) > 0 && (!_networking || _network_server));
241 if (broadcast) {
242 DoCommandP(0, 0, 0, CMD_DESYNC_CHECK);
243 } else {
244 extern void CheckCaches(bool force_check);
245 CheckCaches(true);
248 return true;
251 #ifdef _DEBUG
253 * Reset a tile to bare land in debug mode.
254 * param tile number.
255 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
257 DEF_CONSOLE_CMD(ConResetTile)
259 if (argc == 0) {
260 IConsoleHelp("Reset a tile to bare land. Usage: 'resettile <tile>'");
261 IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)");
262 return true;
265 if (argc == 2) {
266 uint32 result;
267 if (GetArgumentInteger(&result, argv[1])) {
268 DoClearSquare((TileIndex)result);
269 return true;
273 return false;
275 #endif /* _DEBUG */
278 * Scroll to a tile on the map.
279 * @param arg1 tile tile number or tile x coordinate.
280 * @param arg2 optionally tile y coordinate.
281 * @note When only one argument is given it is intepreted as the tile number.
282 * When two arguments are given, they are interpreted as the tile's x
283 * and y coordinates.
284 * @return True when either console help was shown or a proper amount of parameters given.
286 DEF_CONSOLE_CMD(ConScrollToTile)
288 switch (argc) {
289 case 0:
290 IConsoleHelp("Center the screen on a given tile.");
291 IConsoleHelp("Usage: 'scrollto <tile>' or 'scrollto <x> <y>'");
292 IConsoleHelp("Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
293 return true;
295 case 2: {
296 uint32 result;
297 if (GetArgumentInteger(&result, argv[1])) {
298 if (result >= MapSize()) {
299 IConsolePrint(CC_ERROR, "Tile does not exist");
300 return true;
302 ScrollMainWindowToTile((TileIndex)result);
303 return true;
305 break;
308 case 3: {
309 uint32 x, y;
310 if (GetArgumentInteger(&x, argv[1]) && GetArgumentInteger(&y, argv[2])) {
311 if (x >= MapSizeX() || y >= MapSizeY()) {
312 IConsolePrint(CC_ERROR, "Tile does not exist");
313 return true;
315 ScrollMainWindowToTile(TileXY(x, y));
316 return true;
318 break;
322 return false;
326 * Save the map to a file.
327 * @param filename the filename to save the map to.
328 * @return True when help was displayed or the file attempted to be saved.
330 DEF_CONSOLE_CMD(ConSave)
332 if (argc == 0) {
333 IConsoleHelp("Save the current game. Usage: 'save <filename>'");
334 return true;
337 if (argc == 2) {
338 char *filename = str_fmt("%s.sav", argv[1]);
339 IConsolePrint(CC_DEFAULT, "Saving map...");
341 if (SaveOrLoad(filename, SLO_SAVE, DFT_GAME_FILE, SAVE_DIR) != SL_OK) {
342 IConsolePrint(CC_ERROR, "Saving map failed");
343 } else {
344 IConsolePrintF(CC_DEFAULT, "Map successfully saved to %s", filename);
346 free(filename);
347 return true;
350 return false;
354 * Explicitly save the configuration.
355 * @return True.
357 DEF_CONSOLE_CMD(ConSaveConfig)
359 if (argc == 0) {
360 IConsoleHelp("Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
361 IConsoleHelp("It does not save the configuration of the current game to the configuration file.");
362 return true;
365 SaveToConfig();
366 IConsolePrint(CC_DEFAULT, "Saved config.");
367 return true;
370 DEF_CONSOLE_CMD(ConLoad)
372 if (argc == 0) {
373 IConsoleHelp("Load a game by name or index. Usage: 'load <file | number>'");
374 return true;
377 if (argc != 2) return false;
379 const char *file = argv[1];
380 _console_file_list.ValidateFileList();
381 const FiosItem *item = _console_file_list.FindItem(file);
382 if (item != nullptr) {
383 if (GetAbstractFileType(item->type) == FT_SAVEGAME) {
384 _switch_mode = SM_LOAD_GAME;
385 _file_to_saveload.SetMode(item->type);
386 _file_to_saveload.SetName(FiosBrowseTo(item));
387 _file_to_saveload.SetTitle(item->title);
388 } else {
389 IConsolePrintF(CC_ERROR, "%s: Not a savegame.", file);
391 } else {
392 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
395 return true;
399 DEF_CONSOLE_CMD(ConRemove)
401 if (argc == 0) {
402 IConsoleHelp("Remove a savegame by name or index. Usage: 'rm <file | number>'");
403 return true;
406 if (argc != 2) return false;
408 const char *file = argv[1];
409 _console_file_list.ValidateFileList();
410 const FiosItem *item = _console_file_list.FindItem(file);
411 if (item != nullptr) {
412 if (!FiosDelete(item->name)) {
413 IConsolePrintF(CC_ERROR, "%s: Failed to delete file", file);
415 } else {
416 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
419 _console_file_list.InvalidateFileList();
420 return true;
424 /* List all the files in the current dir via console */
425 DEF_CONSOLE_CMD(ConListFiles)
427 if (argc == 0) {
428 IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'");
429 return true;
432 _console_file_list.ValidateFileList(true);
433 for (uint i = 0; i < _console_file_list.Length(); i++) {
434 IConsolePrintF(CC_DEFAULT, "%d) %s", i, _console_file_list[i].title);
437 return true;
440 /* Change the dir via console */
441 DEF_CONSOLE_CMD(ConChangeDirectory)
443 if (argc == 0) {
444 IConsoleHelp("Change the dir via console. Usage: 'cd <directory | number>'");
445 return true;
448 if (argc != 2) return false;
450 const char *file = argv[1];
451 _console_file_list.ValidateFileList(true);
452 const FiosItem *item = _console_file_list.FindItem(file);
453 if (item != nullptr) {
454 switch (item->type) {
455 case FIOS_TYPE_DIR: case FIOS_TYPE_DRIVE: case FIOS_TYPE_PARENT:
456 FiosBrowseTo(item);
457 break;
458 default: IConsolePrintF(CC_ERROR, "%s: Not a directory.", file);
460 } else {
461 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
464 _console_file_list.InvalidateFileList();
465 return true;
468 DEF_CONSOLE_CMD(ConPrintWorkingDirectory)
470 const char *path;
472 if (argc == 0) {
473 IConsoleHelp("Print out the current working directory. Usage: 'pwd'");
474 return true;
477 /* XXX - Workaround for broken file handling */
478 _console_file_list.ValidateFileList(true);
479 _console_file_list.InvalidateFileList();
481 FiosGetDescText(&path, nullptr);
482 IConsolePrint(CC_DEFAULT, path);
483 return true;
486 DEF_CONSOLE_CMD(ConClearBuffer)
488 if (argc == 0) {
489 IConsoleHelp("Clear the console buffer. Usage: 'clear'");
490 return true;
493 IConsoleClearBuffer();
494 SetWindowDirty(WC_CONSOLE, 0);
495 return true;
499 /**********************************
500 * Network Core Console Commands
501 **********************************/
502 #ifdef ENABLE_NETWORK
504 static bool ConKickOrBan(const char *argv, bool ban)
506 uint n;
508 if (strchr(argv, '.') == nullptr && strchr(argv, ':') == nullptr) { // banning with ID
509 ClientID client_id = (ClientID)atoi(argv);
511 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
512 * kicking frees closes and subsequently free the connection related instances, which we
513 * would be reading from and writing to after returning. So we would read or write data
514 * from freed memory up till the segfault triggers. */
515 if (client_id == CLIENT_ID_SERVER || client_id == _redirect_console_to_client) {
516 IConsolePrintF(CC_ERROR, "ERROR: Silly boy, you can not %s yourself!", ban ? "ban" : "kick");
517 return true;
520 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
521 if (ci == nullptr) {
522 IConsoleError("Invalid client");
523 return true;
526 if (!ban) {
527 /* Kick only this client, not all clients with that IP */
528 NetworkServerKickClient(client_id);
529 return true;
532 /* When banning, kick+ban all clients with that IP */
533 n = NetworkServerKickOrBanIP(client_id, ban);
534 } else {
535 n = NetworkServerKickOrBanIP(argv, ban);
538 if (n == 0) {
539 IConsolePrint(CC_DEFAULT, ban ? "Client not online, address added to banlist" : "Client not found");
540 } else {
541 IConsolePrintF(CC_DEFAULT, "%sed %u client(s)", ban ? "Bann" : "Kick", n);
544 return true;
547 DEF_CONSOLE_CMD(ConKick)
549 if (argc == 0) {
550 IConsoleHelp("Kick a client from a network game. Usage: 'kick <ip | client-id>'");
551 IConsoleHelp("For client-id's, see the command 'clients'");
552 return true;
555 if (argc != 2) return false;
557 return ConKickOrBan(argv[1], false);
560 DEF_CONSOLE_CMD(ConBan)
562 if (argc == 0) {
563 IConsoleHelp("Ban a client from a network game. Usage: 'ban <ip | client-id>'");
564 IConsoleHelp("For client-id's, see the command 'clients'");
565 IConsoleHelp("If the client is no longer online, you can still ban his/her IP");
566 return true;
569 if (argc != 2) return false;
571 return ConKickOrBan(argv[1], true);
574 DEF_CONSOLE_CMD(ConUnBan)
576 if (argc == 0) {
577 IConsoleHelp("Unban a client from a network game. Usage: 'unban <ip | banlist-index>'");
578 IConsoleHelp("For a list of banned IP's, see the command 'banlist'");
579 return true;
582 if (argc != 2) return false;
584 /* Try by IP. */
585 uint index;
586 for (index = 0; index < _network_ban_list.Length(); index++) {
587 if (strcmp(_network_ban_list[index], argv[1]) == 0) break;
590 /* Try by index. */
591 if (index >= _network_ban_list.Length()) {
592 index = atoi(argv[1]) - 1U; // let it wrap
595 if (index < _network_ban_list.Length()) {
596 char msg[64];
597 seprintf(msg, lastof(msg), "Unbanned %s", _network_ban_list[index]);
598 IConsolePrint(CC_DEFAULT, msg);
599 free(_network_ban_list[index]);
600 _network_ban_list.Erase(_network_ban_list.Get(index));
601 } else {
602 IConsolePrint(CC_DEFAULT, "Invalid list index or IP not in ban-list.");
603 IConsolePrint(CC_DEFAULT, "For a list of banned IP's, see the command 'banlist'");
606 return true;
609 DEF_CONSOLE_CMD(ConBanList)
611 if (argc == 0) {
612 IConsoleHelp("List the IP's of banned clients: Usage 'banlist'");
613 return true;
616 IConsolePrint(CC_DEFAULT, "Banlist: ");
618 uint i = 1;
619 for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) {
620 IConsolePrintF(CC_DEFAULT, " %d) %s", i, *iter);
623 return true;
626 DEF_CONSOLE_CMD(ConPauseGame)
628 if (argc == 0) {
629 IConsoleHelp("Pause a network game. Usage: 'pause'");
630 return true;
633 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
634 DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
635 if (!_networking) IConsolePrint(CC_DEFAULT, "Game paused.");
636 } else {
637 IConsolePrint(CC_DEFAULT, "Game is already paused.");
640 return true;
643 DEF_CONSOLE_CMD(ConUnpauseGame)
645 if (argc == 0) {
646 IConsoleHelp("Unpause a network game. Usage: 'unpause'");
647 return true;
650 if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) {
651 DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
652 if (!_networking) IConsolePrint(CC_DEFAULT, "Game unpaused.");
653 } else if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED) {
654 IConsolePrint(CC_DEFAULT, "Game is in error state and cannot be unpaused via console.");
655 } else if (_pause_mode != PM_UNPAUSED) {
656 IConsolePrint(CC_DEFAULT, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
657 } else {
658 IConsolePrint(CC_DEFAULT, "Game is already unpaused.");
661 return true;
664 DEF_CONSOLE_CMD(ConRcon)
666 if (argc == 0) {
667 IConsoleHelp("Remote control the server from another client. Usage: 'rcon <password> <command>'");
668 IConsoleHelp("Remember to enclose the command in quotes, otherwise only the first parameter is sent");
669 return true;
672 if (argc < 3) return false;
674 if (_network_server) {
675 IConsoleCmdExec(argv[2]);
676 } else {
677 NetworkClientSendRcon(argv[1], argv[2]);
679 return true;
682 DEF_CONSOLE_CMD(ConStatus)
684 if (argc == 0) {
685 IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
686 return true;
689 NetworkServerShowStatusToConsole();
690 return true;
693 DEF_CONSOLE_CMD(ConServerInfo)
695 if (argc == 0) {
696 IConsoleHelp("List current and maximum client/company limits. Usage 'server_info'");
697 IConsoleHelp("You can change these values by modifying settings 'network.max_clients', 'network.max_companies' and 'network.max_spectators'");
698 return true;
701 IConsolePrintF(CC_DEFAULT, "Current/maximum clients: %2d/%2d", _network_game_info.clients_on, _settings_client.network.max_clients);
702 IConsolePrintF(CC_DEFAULT, "Current/maximum companies: %2d/%2d", (int)Company::GetNumItems(), _settings_client.network.max_companies);
703 IConsolePrintF(CC_DEFAULT, "Current/maximum spectators: %2d/%2d", NetworkSpectatorCount(), _settings_client.network.max_spectators);
705 return true;
708 DEF_CONSOLE_CMD(ConClientNickChange)
710 if (argc != 3) {
711 IConsoleHelp("Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'");
712 IConsoleHelp("For client-id's, see the command 'clients'");
713 return true;
716 ClientID client_id = (ClientID)atoi(argv[1]);
718 if (client_id == CLIENT_ID_SERVER) {
719 IConsoleError("Please use the command 'name' to change your own name!");
720 return true;
723 if (NetworkClientInfo::GetByClientID(client_id) == nullptr) {
724 IConsoleError("Invalid client");
725 return true;
728 if (!NetworkServerChangeClientName(client_id, argv[2])) {
729 IConsoleError("Cannot give a client a duplicate name");
732 return true;
735 DEF_CONSOLE_CMD(ConJoinCompany)
737 if (argc < 2) {
738 IConsoleHelp("Request joining another company. Usage: join <company-id> [<password>]");
739 IConsoleHelp("For valid company-id see company list, use 255 for spectator");
740 return true;
743 CompanyID company_id = (CompanyID)(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1]));
745 /* Check we have a valid company id! */
746 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
747 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
748 return true;
751 if (NetworkClientInfo::GetByClientID(_network_own_client_id)->client_playas == company_id) {
752 IConsoleError("You are already there!");
753 return true;
756 if (company_id == COMPANY_SPECTATOR && NetworkMaxSpectatorsReached()) {
757 IConsoleError("Cannot join spectators, maximum number of spectators reached.");
758 return true;
761 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
762 IConsoleError("Cannot join AI company.");
763 return true;
766 /* Check if the company requires a password */
767 if (NetworkCompanyIsPassworded(company_id) && argc < 3) {
768 IConsolePrintF(CC_ERROR, "Company %d requires a password to join.", company_id + 1);
769 return true;
772 /* non-dedicated server may just do the move! */
773 if (_network_server) {
774 NetworkServerDoMove(CLIENT_ID_SERVER, company_id);
775 } else {
776 NetworkClientRequestMove(company_id, NetworkCompanyIsPassworded(company_id) ? argv[2] : "");
779 return true;
782 DEF_CONSOLE_CMD(ConMoveClient)
784 if (argc < 3) {
785 IConsoleHelp("Move a client to another company. Usage: move <client-id> <company-id>");
786 IConsoleHelp("For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators");
787 return true;
790 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID((ClientID)atoi(argv[1]));
791 CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2]));
793 /* check the client exists */
794 if (ci == nullptr) {
795 IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
796 return true;
799 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
800 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
801 return true;
804 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
805 IConsoleError("You cannot move clients to AI companies.");
806 return true;
809 if (ci->client_id == CLIENT_ID_SERVER && _network_dedicated) {
810 IConsoleError("Silly boy, you cannot move the server!");
811 return true;
814 if (ci->client_playas == company_id) {
815 IConsoleError("You cannot move someone to where he/she already is!");
816 return true;
819 /* we are the server, so force the update */
820 NetworkServerDoMove(ci->client_id, company_id);
822 return true;
825 DEF_CONSOLE_CMD(ConResetCompany)
827 if (argc == 0) {
828 IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company <company-id>'");
829 IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
830 return true;
833 if (argc != 2) return false;
835 CompanyID index = (CompanyID)(atoi(argv[1]) - 1);
837 /* Check valid range */
838 if (!Company::IsValidID(index)) {
839 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
840 return true;
843 if (!Company::IsHumanID(index)) {
844 IConsoleError("Company is owned by an AI.");
845 return true;
848 if (NetworkCompanyHasClients(index)) {
849 IConsoleError("Cannot remove company: a client is connected to that company.");
850 return false;
852 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
853 if (ci->client_playas == index) {
854 IConsoleError("Cannot remove company: the server is connected to that company.");
855 return true;
858 /* It is safe to remove this company */
859 DoCommandP(0, 2 | index << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
860 IConsolePrint(CC_DEFAULT, "Company deleted.");
862 return true;
865 DEF_CONSOLE_CMD(ConNetworkClients)
867 if (argc == 0) {
868 IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'");
869 return true;
872 NetworkPrintClients();
874 return true;
877 DEF_CONSOLE_CMD(ConNetworkReconnect)
879 if (argc == 0) {
880 IConsoleHelp("Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'");
881 IConsoleHelp("Company 255 is spectator (default, if not specified), 0 means creating new company.");
882 IConsoleHelp("All others are a certain company with Company 1 being #1");
883 return true;
886 CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR;
887 switch (playas) {
888 case 0: playas = COMPANY_NEW_COMPANY; break;
889 case COMPANY_SPECTATOR: /* nothing to do */ break;
890 default:
891 /* From a user pov 0 is a new company, internally it's different and all
892 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
893 playas--;
894 if (playas < COMPANY_FIRST || playas >= MAX_COMPANIES) return false;
895 break;
898 if (StrEmpty(_settings_client.network.last_host)) {
899 IConsolePrint(CC_DEFAULT, "No server for reconnecting.");
900 return true;
903 /* Don't resolve the address first, just print it directly as it comes from the config file. */
904 IConsolePrintF(CC_DEFAULT, "Reconnecting to %s:%d...", _settings_client.network.last_host, _settings_client.network.last_port);
906 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), playas);
907 return true;
910 DEF_CONSOLE_CMD(ConNetworkConnect)
912 if (argc == 0) {
913 IConsoleHelp("Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'");
914 IConsoleHelp("IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'");
915 IConsoleHelp("Company #255 is spectator all others are a certain company with Company 1 being #1");
916 return true;
919 if (argc < 2) return false;
920 if (_networking) NetworkDisconnect(); // we are in network-mode, first close it!
922 const char *port = nullptr;
923 const char *company = nullptr;
924 char *ip = argv[1];
925 /* Default settings: default port and new company */
926 uint16 rport = NETWORK_DEFAULT_PORT;
927 CompanyID join_as = COMPANY_NEW_COMPANY;
929 ParseConnectionString(&company, &port, ip);
931 IConsolePrintF(CC_DEFAULT, "Connecting to %s...", ip);
932 if (company != nullptr) {
933 join_as = (CompanyID)atoi(company);
934 IConsolePrintF(CC_DEFAULT, " company-no: %d", join_as);
936 /* From a user pov 0 is a new company, internally it's different and all
937 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
938 if (join_as != COMPANY_SPECTATOR) {
939 if (join_as > MAX_COMPANIES) return false;
940 join_as--;
943 if (port != nullptr) {
944 rport = atoi(port);
945 IConsolePrintF(CC_DEFAULT, " port: %s", port);
948 NetworkClientConnectGame(NetworkAddress(ip, rport), join_as);
950 return true;
953 #endif /* ENABLE_NETWORK */
955 /*********************************
956 * script file console commands
957 *********************************/
959 DEF_CONSOLE_CMD(ConExec)
961 if (argc == 0) {
962 IConsoleHelp("Execute a local script file. Usage: 'exec <script> <?>'");
963 return true;
966 if (argc < 2) return false;
968 FILE *script_file = FioFOpenFile(argv[1], "r", BASE_DIR);
970 if (script_file == nullptr) {
971 if (argc == 2 || atoi(argv[2]) != 0) IConsoleError("script file not found");
972 return true;
975 _script_running = true;
977 char cmdline[ICON_CMDLN_SIZE];
978 while (_script_running && fgets(cmdline, sizeof(cmdline), script_file) != nullptr) {
979 /* Remove newline characters from the executing script */
980 for (char *cmdptr = cmdline; *cmdptr != '\0'; cmdptr++) {
981 if (*cmdptr == '\n' || *cmdptr == '\r') {
982 *cmdptr = '\0';
983 break;
986 IConsoleCmdExec(cmdline);
989 if (ferror(script_file)) {
990 IConsoleError("Encountered error while trying to read from script file");
993 _script_running = false;
994 FioFCloseFile(script_file);
995 return true;
998 DEF_CONSOLE_CMD(ConReturn)
1000 if (argc == 0) {
1001 IConsoleHelp("Stop executing a running script. Usage: 'return'");
1002 return true;
1005 _script_running = false;
1006 return true;
1009 /*****************************
1010 * default console commands
1011 ******************************/
1012 extern bool CloseConsoleLogIfActive();
1014 DEF_CONSOLE_CMD(ConScript)
1016 extern FILE *_iconsole_output_file;
1018 if (argc == 0) {
1019 IConsoleHelp("Start or stop logging console output to a file. Usage: 'script <filename>'");
1020 IConsoleHelp("If filename is omitted, a running log is stopped if it is active");
1021 return true;
1024 if (!CloseConsoleLogIfActive()) {
1025 if (argc < 2) return false;
1027 IConsolePrintF(CC_DEFAULT, "file output started to: %s", argv[1]);
1028 _iconsole_output_file = fopen(argv[1], "ab");
1029 if (_iconsole_output_file == nullptr) IConsoleError("could not open file");
1032 return true;
1036 DEF_CONSOLE_CMD(ConEcho)
1038 if (argc == 0) {
1039 IConsoleHelp("Print back the first argument to the console. Usage: 'echo <arg>'");
1040 return true;
1043 if (argc < 2) return false;
1044 IConsolePrint(CC_DEFAULT, argv[1]);
1045 return true;
1048 DEF_CONSOLE_CMD(ConEchoC)
1050 if (argc == 0) {
1051 IConsoleHelp("Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'");
1052 return true;
1055 if (argc < 3) return false;
1056 IConsolePrint((TextColour)Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1), argv[2]);
1057 return true;
1060 DEF_CONSOLE_CMD(ConNewGame)
1062 if (argc == 0) {
1063 IConsoleHelp("Start a new game. Usage: 'newgame [seed]'");
1064 IConsoleHelp("The server can force a new game using 'newgame'; any client joined will rejoin after the server is done generating the new game.");
1065 return true;
1068 StartNewGameWithoutGUI((argc == 2) ? strtoul(argv[1], nullptr, 10) : GENERATE_NEW_SEED);
1069 return true;
1072 DEF_CONSOLE_CMD(ConRestart)
1074 if (argc == 0) {
1075 IConsoleHelp("Restart game. Usage: 'restart'");
1076 IConsoleHelp("Restarts a game. It tries to reproduce the exact same map as the game started with.");
1077 IConsoleHelp("However:");
1078 IConsoleHelp(" * restarting games started in another version might create another map due to difference in map generation");
1079 IConsoleHelp(" * restarting games based on scenarios, loaded games or heightmaps will start a new game based on the settings stored in the scenario/savegame");
1080 return true;
1083 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1084 _settings_game.game_creation.map_x = MapLogX();
1085 _settings_game.game_creation.map_y = FindFirstBit(MapSizeY());
1086 _switch_mode = SM_RESTARTGAME;
1087 return true;
1091 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1092 * @param buf The buffer to print.
1093 * @note All newlines are replace by '\0' characters.
1095 static void PrintLineByLine(char *buf)
1097 char *p = buf;
1098 /* Print output line by line */
1099 for (char *p2 = buf; *p2 != '\0'; p2++) {
1100 if (*p2 == '\n') {
1101 *p2 = '\0';
1102 IConsolePrintF(CC_DEFAULT, "%s", p);
1103 p = p2 + 1;
1108 DEF_CONSOLE_CMD(ConListAILibs)
1110 char buf[4096];
1111 AI::GetConsoleLibraryList(buf, lastof(buf));
1113 PrintLineByLine(buf);
1115 return true;
1118 DEF_CONSOLE_CMD(ConListAI)
1120 char buf[4096];
1121 AI::GetConsoleList(buf, lastof(buf));
1123 PrintLineByLine(buf);
1125 return true;
1128 DEF_CONSOLE_CMD(ConListGameLibs)
1130 char buf[4096];
1131 Game::GetConsoleLibraryList(buf, lastof(buf));
1133 PrintLineByLine(buf);
1135 return true;
1138 DEF_CONSOLE_CMD(ConListGame)
1140 char buf[4096];
1141 Game::GetConsoleList(buf, lastof(buf));
1143 PrintLineByLine(buf);
1145 return true;
1148 DEF_CONSOLE_CMD(ConStartAI)
1150 if (argc == 0 || argc > 3) {
1151 IConsoleHelp("Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'");
1152 IConsoleHelp("Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1153 IConsoleHelp("If <settings> is given, it is parsed and the AI settings are set to that.");
1154 return true;
1157 if (_game_mode != GM_NORMAL) {
1158 IConsoleWarning("AIs can only be managed in a game.");
1159 return true;
1162 if (Company::GetNumItems() == CompanyPool::MAX_SIZE) {
1163 IConsoleWarning("Can't start a new AI (no more free slots).");
1164 return true;
1166 if (_networking && !_network_server) {
1167 IConsoleWarning("Only the server can start a new AI.");
1168 return true;
1170 if (_networking && !_settings_game.ai.ai_in_multiplayer) {
1171 IConsoleWarning("AIs are not allowed in multiplayer by configuration.");
1172 IConsoleWarning("Switch AI -> AI in multiplayer to True.");
1173 return true;
1175 if (!AI::CanStartNew()) {
1176 IConsoleWarning("Can't start a new AI.");
1177 return true;
1180 int n = 0;
1181 Company *c;
1182 /* Find the next free slot */
1183 FOR_ALL_COMPANIES(c) {
1184 if (c->index != n) break;
1185 n++;
1188 AIConfig *config = AIConfig::GetConfig((CompanyID)n);
1189 if (argc >= 2) {
1190 config->Change(argv[1], -1, true);
1191 if (!config->HasScript()) {
1192 IConsoleWarning("Failed to load the specified AI");
1193 return true;
1195 if (argc == 3) {
1196 config->StringToSettings(argv[2]);
1200 /* Start a new AI company */
1201 DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
1203 return true;
1206 DEF_CONSOLE_CMD(ConReloadAI)
1208 if (argc != 2) {
1209 IConsoleHelp("Reload an AI. Usage: 'reload_ai <company-id>'");
1210 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.");
1211 return true;
1214 if (_game_mode != GM_NORMAL) {
1215 IConsoleWarning("AIs can only be managed in a game.");
1216 return true;
1219 if (_networking && !_network_server) {
1220 IConsoleWarning("Only the server can reload an AI.");
1221 return true;
1224 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1225 if (!Company::IsValidID(company_id)) {
1226 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1227 return true;
1230 if (Company::IsHumanID(company_id)) {
1231 IConsoleWarning("Company is not controlled by an AI.");
1232 return true;
1235 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1236 DoCommandP(0, 2 | company_id << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
1237 DoCommandP(0, 1 | company_id << 16, 0, CMD_COMPANY_CTRL);
1238 IConsolePrint(CC_DEFAULT, "AI reloaded.");
1240 return true;
1243 DEF_CONSOLE_CMD(ConStopAI)
1245 if (argc != 2) {
1246 IConsoleHelp("Stop an AI. Usage: 'stop_ai <company-id>'");
1247 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.");
1248 return true;
1251 if (_game_mode != GM_NORMAL) {
1252 IConsoleWarning("AIs can only be managed in a game.");
1253 return true;
1256 if (_networking && !_network_server) {
1257 IConsoleWarning("Only the server can stop an AI.");
1258 return true;
1261 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1262 if (!Company::IsValidID(company_id)) {
1263 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1264 return true;
1267 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1268 IConsoleWarning("Company is not controlled by an AI.");
1269 return true;
1272 /* Now kill the company of the AI. */
1273 DoCommandP(0, 2 | company_id << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
1274 IConsolePrint(CC_DEFAULT, "AI stopped, company deleted.");
1276 return true;
1279 DEF_CONSOLE_CMD(ConRescanAI)
1281 if (argc == 0) {
1282 IConsoleHelp("Rescan the AI dir for scripts. Usage: 'rescan_ai'");
1283 return true;
1286 if (_networking && !_network_server) {
1287 IConsoleWarning("Only the server can rescan the AI dir for scripts.");
1288 return true;
1291 AI::Rescan();
1293 return true;
1296 DEF_CONSOLE_CMD(ConRescanGame)
1298 if (argc == 0) {
1299 IConsoleHelp("Rescan the Game Script dir for scripts. Usage: 'rescan_game'");
1300 return true;
1303 if (_networking && !_network_server) {
1304 IConsoleWarning("Only the server can rescan the Game Script dir for scripts.");
1305 return true;
1308 Game::Rescan();
1310 return true;
1313 DEF_CONSOLE_CMD(ConRescanNewGRF)
1315 if (argc == 0) {
1316 IConsoleHelp("Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'");
1317 return true;
1320 ScanNewGRFFiles(nullptr);
1322 return true;
1325 DEF_CONSOLE_CMD(ConGetSeed)
1327 if (argc == 0) {
1328 IConsoleHelp("Returns the seed used to create this game. Usage: 'getseed'");
1329 IConsoleHelp("The seed can be used to reproduce the exact same map as the game started with.");
1330 return true;
1333 IConsolePrintF(CC_DEFAULT, "Generation Seed: %u", _settings_game.game_creation.generation_seed);
1334 return true;
1337 DEF_CONSOLE_CMD(ConGetDate)
1339 if (argc == 0) {
1340 IConsoleHelp("Returns the current date (day-month-year) of the game. Usage: 'getdate'");
1341 return true;
1344 IConsolePrintF(CC_DEFAULT, "Date: %d-%d-%d", _cur_date_ymd.day, _cur_date_ymd.month + 1, _cur_date_ymd.year);
1345 return true;
1349 DEF_CONSOLE_CMD(ConAlias)
1351 IConsoleAlias *alias;
1353 if (argc == 0) {
1354 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1355 return true;
1358 if (argc < 3) return false;
1360 alias = IConsoleAliasGet(argv[1]);
1361 if (alias == nullptr) {
1362 IConsoleAliasRegister(argv[1], argv[2]);
1363 } else {
1364 free(alias->cmdline);
1365 alias->cmdline = stredup(argv[2]);
1367 return true;
1370 DEF_CONSOLE_CMD(ConScreenShot)
1372 if (argc == 0) {
1373 IConsoleHelp("Create a screenshot of the game. Usage: 'screenshot [big | giant | no_con] [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 return true;
1380 if (argc > 3) return false;
1382 ScreenshotType type = SC_VIEWPORT;
1383 const char *name = nullptr;
1385 if (argc > 1) {
1386 if (strcmp(argv[1], "big") == 0) {
1387 /* screenshot big [filename] */
1388 type = SC_ZOOMEDIN;
1389 if (argc > 2) name = argv[2];
1390 } else if (strcmp(argv[1], "giant") == 0) {
1391 /* screenshot giant [filename] */
1392 type = SC_WORLD;
1393 if (argc > 2) name = argv[2];
1394 } else if (strcmp(argv[1], "no_con") == 0) {
1395 /* screenshot no_con [filename] */
1396 IConsoleClose();
1397 if (argc > 2) name = argv[2];
1398 } else if (argc == 2) {
1399 /* screenshot filename */
1400 name = argv[1];
1401 } else {
1402 /* screenshot argv[1] argv[2] - invalid */
1403 return false;
1407 MakeScreenshot(type, name);
1408 return true;
1411 DEF_CONSOLE_CMD(ConMinimap)
1413 if (argc == 0) {
1414 IConsoleHelp("Create a flat image of the game minimap. Usage: 'minimap [owner] [file name]'");
1415 IConsoleHelp("'owner' uses the tile owner to colour the minimap image, this is the only mode at present");
1416 return true;
1419 const char *name = nullptr;
1420 if (argc > 1) {
1421 if (strcmp(argv[1], "owner") != 0) {
1422 /* invalid mode */
1423 return false;
1426 if (argc > 2) {
1427 name = argv[2];
1430 return MakeScreenshot(SC_MINIMAP, name);
1433 DEF_CONSOLE_CMD(ConInfoCmd)
1435 if (argc == 0) {
1436 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1437 return true;
1440 if (argc < 2) return false;
1442 const IConsoleCmd *cmd = IConsoleCmdGet(argv[1]);
1443 if (cmd == nullptr) {
1444 IConsoleError("the given command was not found");
1445 return true;
1448 IConsolePrintF(CC_DEFAULT, "command name: %s", cmd->name);
1449 IConsolePrintF(CC_DEFAULT, "command proc: %p", cmd->proc);
1451 if (cmd->hook != nullptr) IConsoleWarning("command is hooked");
1453 return true;
1456 DEF_CONSOLE_CMD(ConDebugLevel)
1458 if (argc == 0) {
1459 IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
1460 IConsoleHelp("Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'s");
1461 return true;
1464 if (argc > 2) return false;
1466 if (argc == 1) {
1467 IConsolePrintF(CC_DEFAULT, "Current debug-level: '%s'", GetDebugString());
1468 } else {
1469 SetDebugString(argv[1]);
1472 return true;
1475 DEF_CONSOLE_CMD(ConExit)
1477 if (argc == 0) {
1478 IConsoleHelp("Exit the game. Usage: 'exit'");
1479 return true;
1482 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
1484 _exit_game = true;
1485 return true;
1488 DEF_CONSOLE_CMD(ConPart)
1490 if (argc == 0) {
1491 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1492 return true;
1495 if (_game_mode != GM_NORMAL) return false;
1497 _switch_mode = SM_MENU;
1498 return true;
1501 DEF_CONSOLE_CMD(ConHelp)
1503 if (argc == 2) {
1504 const IConsoleCmd *cmd;
1505 const IConsoleAlias *alias;
1507 RemoveUnderscores(argv[1]);
1508 cmd = IConsoleCmdGet(argv[1]);
1509 if (cmd != nullptr) {
1510 cmd->proc(0, nullptr);
1511 return true;
1514 alias = IConsoleAliasGet(argv[1]);
1515 if (alias != nullptr) {
1516 cmd = IConsoleCmdGet(alias->cmdline);
1517 if (cmd != nullptr) {
1518 cmd->proc(0, nullptr);
1519 return true;
1521 IConsolePrintF(CC_ERROR, "ERROR: alias is of special type, please see its execution-line: '%s'", alias->cmdline);
1522 return true;
1525 IConsoleError("command not found");
1526 return true;
1529 IConsolePrint(CC_WARNING, " ---- OpenTTD Console Help ---- ");
1530 IConsolePrint(CC_DEFAULT, " - commands: [command to list all commands: list_cmds]");
1531 IConsolePrint(CC_DEFAULT, " call commands with '<command> <arg2> <arg3>...'");
1532 IConsolePrint(CC_DEFAULT, " - to assign strings, or use them as arguments, enclose it within quotes");
1533 IConsolePrint(CC_DEFAULT, " like this: '<command> \"string argument with spaces\"'");
1534 IConsolePrint(CC_DEFAULT, " - use 'help <command>' to get specific information");
1535 IConsolePrint(CC_DEFAULT, " - scroll console output with shift + (up | down | pageup | pagedown)");
1536 IConsolePrint(CC_DEFAULT, " - scroll console input history with the up or down arrows");
1537 IConsolePrint(CC_DEFAULT, "");
1538 return true;
1541 DEF_CONSOLE_CMD(ConListCommands)
1543 if (argc == 0) {
1544 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1545 return true;
1548 for (const IConsoleCmd *cmd = _iconsole_cmds; cmd != nullptr; cmd = cmd->next) {
1549 if (argv[1] == nullptr || strstr(cmd->name, argv[1]) != nullptr) {
1550 if (cmd->hook == nullptr || cmd->hook(false) != CHR_HIDE) IConsolePrintF(CC_DEFAULT, "%s", cmd->name);
1554 return true;
1557 DEF_CONSOLE_CMD(ConListAliases)
1559 if (argc == 0) {
1560 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1561 return true;
1564 for (const IConsoleAlias *alias = _iconsole_aliases; alias != nullptr; alias = alias->next) {
1565 if (argv[1] == nullptr || strstr(alias->name, argv[1]) != nullptr) {
1566 IConsolePrintF(CC_DEFAULT, "%s => %s", alias->name, alias->cmdline);
1570 return true;
1573 DEF_CONSOLE_CMD(ConCompanies)
1575 if (argc == 0) {
1576 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1577 return true;
1580 Company *c;
1581 FOR_ALL_COMPANIES(c) {
1582 /* Grab the company name */
1583 char company_name[512];
1584 SetDParam(0, c->index);
1585 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1587 const char *password_state = "";
1588 if (c->is_ai) {
1589 password_state = "AI";
1591 #ifdef ENABLE_NETWORK
1592 else if (_network_server) {
1593 password_state = StrEmpty(_network_company_states[c->index].password) ? "unprotected" : "protected";
1595 #endif
1597 char colour[512];
1598 GetString(colour, STR_COLOUR_DARK_BLUE + _company_colours[c->index], lastof(colour));
1599 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",
1600 c->index + 1, colour, company_name,
1601 c->inaugurated_year, (int64)c->money, (int64)c->current_loan, (int64)CalculateCompanyValue(c),
1602 c->group_all[VEH_TRAIN].num_vehicle,
1603 c->group_all[VEH_ROAD].num_vehicle,
1604 c->group_all[VEH_AIRCRAFT].num_vehicle,
1605 c->group_all[VEH_SHIP].num_vehicle,
1606 password_state);
1609 return true;
1612 #ifdef ENABLE_NETWORK
1614 DEF_CONSOLE_CMD(ConSay)
1616 if (argc == 0) {
1617 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1618 return true;
1621 if (argc != 2) return false;
1623 if (!_network_server) {
1624 NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
1625 } else {
1626 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1627 NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin);
1630 return true;
1633 DEF_CONSOLE_CMD(ConSayCompany)
1635 if (argc == 0) {
1636 IConsoleHelp("Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'");
1637 IConsoleHelp("CompanyNo is the company that plays as company <companyno>, 1 through max_companies");
1638 return true;
1641 if (argc != 3) return false;
1643 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1644 if (!Company::IsValidID(company_id)) {
1645 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1646 return true;
1649 if (!_network_server) {
1650 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]);
1651 } else {
1652 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1653 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2], CLIENT_ID_SERVER, from_admin);
1656 return true;
1659 DEF_CONSOLE_CMD(ConSayClient)
1661 if (argc == 0) {
1662 IConsoleHelp("Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'");
1663 IConsoleHelp("For client-id's, see the command 'clients'");
1664 return true;
1667 if (argc != 3) return false;
1669 if (!_network_server) {
1670 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
1671 } else {
1672 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1673 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin);
1676 return true;
1679 DEF_CONSOLE_CMD(ConCompanyPassword)
1681 if (argc == 0) {
1682 const char *helpmsg;
1684 if (_network_dedicated) {
1685 helpmsg = "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\"";
1686 } else if (_network_server) {
1687 helpmsg = "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'";
1688 } else {
1689 helpmsg = "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1692 IConsoleHelp(helpmsg);
1693 IConsoleHelp("Use \"*\" to disable the password.");
1694 return true;
1697 CompanyID company_id;
1698 const char *password;
1699 const char *errormsg;
1701 if (argc == 2) {
1702 company_id = _local_company;
1703 password = argv[1];
1704 errormsg = "You have to own a company to make use of this command.";
1705 } else if (argc == 3 && _network_server) {
1706 company_id = (CompanyID)(atoi(argv[1]) - 1);
1707 password = argv[2];
1708 errormsg = "You have to specify the ID of a valid human controlled company.";
1709 } else {
1710 return false;
1713 if (!Company::IsValidHumanID(company_id)) {
1714 IConsoleError(errormsg);
1715 return false;
1718 password = NetworkChangeCompanyPassword(company_id, password);
1720 if (StrEmpty(password)) {
1721 IConsolePrintF(CC_WARNING, "Company password cleared");
1722 } else {
1723 IConsolePrintF(CC_WARNING, "Company password changed to: %s", password);
1726 return true;
1729 /* Content downloading only is available with ZLIB */
1730 #if defined(WITH_ZLIB)
1731 #include "network/network_content.h"
1733 /** Resolve a string to a content type. */
1734 static ContentType StringToContentType(const char *str)
1736 static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1737 for (uint i = 1 /* there is no type 0 */; i < lengthof(inv_lookup); i++) {
1738 if (strcasecmp(str, inv_lookup[i]) == 0) return (ContentType)i;
1740 return CONTENT_TYPE_END;
1743 /** Asynchronous callback */
1744 struct ConsoleContentCallback : public ContentCallback {
1745 void OnConnect(bool success)
1747 IConsolePrintF(CC_DEFAULT, "Content server connection %s", success ? "established" : "failed");
1750 void OnDisconnect()
1752 IConsolePrintF(CC_DEFAULT, "Content server connection closed");
1755 void OnDownloadComplete(ContentID cid)
1757 IConsolePrintF(CC_DEFAULT, "Completed download of %d", cid);
1762 * Outputs content state information to console
1763 * @param ci the content info
1765 static void OutputContentState(const ContentInfo *const ci)
1767 static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1768 assert_compile(lengthof(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN);
1769 static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1770 static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR };
1772 char buf[sizeof(ci->md5sum) * 2 + 1];
1773 md5sumToString(buf, lastof(buf), ci->md5sum);
1774 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);
1777 DEF_CONSOLE_CMD(ConContent)
1779 static ContentCallback *cb = nullptr;
1780 if (cb == nullptr) {
1781 cb = new ConsoleContentCallback();
1782 _network_content_client.AddCallback(cb);
1785 if (argc <= 1) {
1786 IConsoleHelp("Query, select and download content. Usage: 'content update|upgrade|select [all|id]|unselect [all|id]|state [filter]|download'");
1787 IConsoleHelp(" update: get a new list of downloadable content; must be run first");
1788 IConsoleHelp(" upgrade: select all items that are upgrades");
1789 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");
1790 IConsoleHelp(" unselect: unselect a specific item given by its id or 'all' to unselect all");
1791 IConsoleHelp(" state: show the download/select state of all downloadable content. Optionally give a filter string");
1792 IConsoleHelp(" download: download all content you've selected");
1793 return true;
1796 if (strcasecmp(argv[1], "update") == 0) {
1797 _network_content_client.RequestContentList((argc > 2) ? StringToContentType(argv[2]) : CONTENT_TYPE_END);
1798 return true;
1801 if (strcasecmp(argv[1], "upgrade") == 0) {
1802 _network_content_client.SelectUpgrade();
1803 return true;
1806 if (strcasecmp(argv[1], "select") == 0) {
1807 if (argc <= 2) {
1808 /* List selected content */
1809 IConsolePrintF(CC_WHITE, "id, type, state, name");
1810 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1811 if ((*iter)->state != ContentInfo::SELECTED && (*iter)->state != ContentInfo::AUTOSELECTED) continue;
1812 OutputContentState(*iter);
1814 } else if (strcasecmp(argv[2], "all") == 0) {
1815 _network_content_client.SelectAll();
1816 } else {
1817 _network_content_client.Select((ContentID)atoi(argv[2]));
1819 return true;
1822 if (strcasecmp(argv[1], "unselect") == 0) {
1823 if (argc <= 2) {
1824 IConsoleError("You must enter the id.");
1825 return false;
1827 if (strcasecmp(argv[2], "all") == 0) {
1828 _network_content_client.UnselectAll();
1829 } else {
1830 _network_content_client.Unselect((ContentID)atoi(argv[2]));
1832 return true;
1835 if (strcasecmp(argv[1], "state") == 0) {
1836 IConsolePrintF(CC_WHITE, "id, type, state, name");
1837 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1838 if (argc > 2 && strcasestr((*iter)->name, argv[2]) == nullptr) continue;
1839 OutputContentState(*iter);
1841 return true;
1844 if (strcasecmp(argv[1], "download") == 0) {
1845 uint files;
1846 uint bytes;
1847 _network_content_client.DownloadSelectedContent(files, bytes);
1848 IConsolePrintF(CC_DEFAULT, "Downloading %d file(s) (%d bytes)", files, bytes);
1849 return true;
1852 return false;
1854 #endif /* defined(WITH_ZLIB) */
1855 #endif /* ENABLE_NETWORK */
1857 DEF_CONSOLE_CMD(ConSetting)
1859 if (argc == 0) {
1860 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1861 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1862 return true;
1865 if (argc == 1 || argc > 3) return false;
1867 if (argc == 2) {
1868 IConsoleGetSetting(argv[1]);
1869 } else {
1870 IConsoleSetSetting(argv[1], argv[2]);
1873 return true;
1876 DEF_CONSOLE_CMD(ConSettingNewgame)
1878 if (argc == 0) {
1879 IConsoleHelp("Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'");
1880 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1881 return true;
1884 if (argc == 1 || argc > 3) return false;
1886 if (argc == 2) {
1887 IConsoleGetSetting(argv[1], true);
1888 } else {
1889 IConsoleSetSetting(argv[1], argv[2], true);
1892 return true;
1895 DEF_CONSOLE_CMD(ConListSettings)
1897 if (argc == 0) {
1898 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1899 return true;
1902 if (argc > 2) return false;
1904 IConsoleListSettings((argc == 2) ? argv[1] : nullptr);
1905 return true;
1908 DEF_CONSOLE_CMD(ConGamelogPrint)
1910 GamelogPrintConsole();
1911 return true;
1914 DEF_CONSOLE_CMD(ConNewGRFReload)
1916 if (argc == 0) {
1917 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1918 return true;
1921 ReloadNewGRFData();
1923 extern void PostCheckNewGRFLoadWarnings();
1924 PostCheckNewGRFLoadWarnings();
1925 return true;
1928 DEF_CONSOLE_CMD(ConDumpCommandLog)
1930 if (argc == 0) {
1931 IConsoleHelp("Dump log of recently executed commands.");
1932 return true;
1935 char buffer[32768];
1936 DumpCommandLog(buffer, lastof(buffer));
1937 PrintLineByLine(buffer);
1938 return true;
1941 #ifdef _DEBUG
1942 /******************
1943 * debug commands
1944 ******************/
1946 static void IConsoleDebugLibRegister()
1948 IConsoleCmdRegister("resettile", ConResetTile);
1949 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
1950 IConsoleAliasRegister("dbg_echo2", "echo %!");
1952 #endif
1954 /*******************************
1955 * console command registration
1956 *******************************/
1958 void IConsoleStdLibRegister()
1960 IConsoleCmdRegister("debug_level", ConDebugLevel);
1961 IConsoleCmdRegister("echo", ConEcho);
1962 IConsoleCmdRegister("echoc", ConEchoC);
1963 IConsoleCmdRegister("exec", ConExec);
1964 IConsoleCmdRegister("exit", ConExit);
1965 IConsoleCmdRegister("part", ConPart);
1966 IConsoleCmdRegister("help", ConHelp);
1967 IConsoleCmdRegister("info_cmd", ConInfoCmd);
1968 IConsoleCmdRegister("list_cmds", ConListCommands);
1969 IConsoleCmdRegister("list_aliases", ConListAliases);
1970 IConsoleCmdRegister("newgame", ConNewGame);
1971 IConsoleCmdRegister("restart", ConRestart);
1972 IConsoleCmdRegister("getseed", ConGetSeed);
1973 IConsoleCmdRegister("getdate", ConGetDate);
1974 IConsoleCmdRegister("quit", ConExit);
1975 IConsoleCmdRegister("resetengines", ConResetEngines, ConHookNoNetwork);
1976 IConsoleCmdRegister("reset_enginepool", ConResetEnginePool, ConHookNoNetwork);
1977 IConsoleCmdRegister("return", ConReturn);
1978 IConsoleCmdRegister("screenshot", ConScreenShot);
1979 IConsoleCmdRegister("minimap", ConMinimap);
1980 IConsoleCmdRegister("script", ConScript);
1981 IConsoleCmdRegister("scrollto", ConScrollToTile);
1982 IConsoleCmdRegister("alias", ConAlias);
1983 IConsoleCmdRegister("load", ConLoad);
1984 IConsoleCmdRegister("rm", ConRemove);
1985 IConsoleCmdRegister("save", ConSave);
1986 IConsoleCmdRegister("saveconfig", ConSaveConfig);
1987 IConsoleCmdRegister("ls", ConListFiles);
1988 IConsoleCmdRegister("cd", ConChangeDirectory);
1989 IConsoleCmdRegister("pwd", ConPrintWorkingDirectory);
1990 IConsoleCmdRegister("clear", ConClearBuffer);
1991 IConsoleCmdRegister("setting", ConSetting);
1992 IConsoleCmdRegister("setting_newgame", ConSettingNewgame);
1993 IConsoleCmdRegister("list_settings",ConListSettings);
1994 IConsoleCmdRegister("gamelog", ConGamelogPrint);
1995 IConsoleCmdRegister("rescan_newgrf", ConRescanNewGRF);
1997 IConsoleAliasRegister("dir", "ls");
1998 IConsoleAliasRegister("del", "rm %+");
1999 IConsoleAliasRegister("newmap", "newgame");
2000 IConsoleAliasRegister("patch", "setting %+");
2001 IConsoleAliasRegister("set", "setting %+");
2002 IConsoleAliasRegister("set_newgame", "setting_newgame %+");
2003 IConsoleAliasRegister("list_patches", "list_settings %+");
2004 IConsoleAliasRegister("developer", "setting developer %+");
2006 IConsoleCmdRegister("list_ai_libs", ConListAILibs);
2007 IConsoleCmdRegister("list_ai", ConListAI);
2008 IConsoleCmdRegister("reload_ai", ConReloadAI);
2009 IConsoleCmdRegister("rescan_ai", ConRescanAI);
2010 IConsoleCmdRegister("start_ai", ConStartAI);
2011 IConsoleCmdRegister("stop_ai", ConStopAI);
2013 IConsoleCmdRegister("list_game", ConListGame);
2014 IConsoleCmdRegister("list_game_libs", ConListGameLibs);
2015 IConsoleCmdRegister("rescan_game", ConRescanGame);
2017 IConsoleCmdRegister("companies", ConCompanies);
2018 IConsoleAliasRegister("players", "companies");
2020 /* networking functions */
2021 #ifdef ENABLE_NETWORK
2022 /* Content downloading is only available with ZLIB */
2023 #if defined(WITH_ZLIB)
2024 IConsoleCmdRegister("content", ConContent);
2025 #endif /* defined(WITH_ZLIB) */
2027 /*** Networking commands ***/
2028 IConsoleCmdRegister("say", ConSay, ConHookNeedNetwork);
2029 IConsoleCmdRegister("say_company", ConSayCompany, ConHookNeedNetwork);
2030 IConsoleAliasRegister("say_player", "say_company %+");
2031 IConsoleCmdRegister("say_client", ConSayClient, ConHookNeedNetwork);
2033 IConsoleCmdRegister("connect", ConNetworkConnect, ConHookClientOnly);
2034 IConsoleCmdRegister("clients", ConNetworkClients, ConHookNeedNetwork);
2035 IConsoleCmdRegister("status", ConStatus, ConHookServerOnly);
2036 IConsoleCmdRegister("server_info", ConServerInfo, ConHookServerOnly);
2037 IConsoleAliasRegister("info", "server_info");
2038 IConsoleCmdRegister("reconnect", ConNetworkReconnect, ConHookClientOnly);
2039 IConsoleCmdRegister("rcon", ConRcon, ConHookNeedNetwork);
2041 IConsoleCmdRegister("join", ConJoinCompany, ConHookNeedNetwork);
2042 IConsoleAliasRegister("spectate", "join 255");
2043 IConsoleCmdRegister("move", ConMoveClient, ConHookServerOnly);
2044 IConsoleCmdRegister("reset_company", ConResetCompany, ConHookServerOnly);
2045 IConsoleAliasRegister("clean_company", "reset_company %A");
2046 IConsoleCmdRegister("client_name", ConClientNickChange, ConHookServerOnly);
2047 IConsoleCmdRegister("kick", ConKick, ConHookServerOnly);
2048 IConsoleCmdRegister("ban", ConBan, ConHookServerOnly);
2049 IConsoleCmdRegister("unban", ConUnBan, ConHookServerOnly);
2050 IConsoleCmdRegister("banlist", ConBanList, ConHookServerOnly);
2052 IConsoleCmdRegister("pause", ConPauseGame, ConHookServerOnly);
2053 IConsoleCmdRegister("unpause", ConUnpauseGame, ConHookServerOnly);
2055 IConsoleCmdRegister("company_pw", ConCompanyPassword, ConHookNeedNetwork);
2056 IConsoleAliasRegister("company_password", "company_pw %+");
2058 IConsoleAliasRegister("net_frame_freq", "setting frame_freq %+");
2059 IConsoleAliasRegister("net_sync_freq", "setting sync_freq %+");
2060 IConsoleAliasRegister("server_pw", "setting server_password %+");
2061 IConsoleAliasRegister("server_password", "setting server_password %+");
2062 IConsoleAliasRegister("rcon_pw", "setting rcon_password %+");
2063 IConsoleAliasRegister("rcon_password", "setting rcon_password %+");
2064 IConsoleAliasRegister("name", "setting client_name %+");
2065 IConsoleAliasRegister("server_name", "setting server_name %+");
2066 IConsoleAliasRegister("server_port", "setting server_port %+");
2067 IConsoleAliasRegister("server_advertise", "setting server_advertise %+");
2068 IConsoleAliasRegister("max_clients", "setting max_clients %+");
2069 IConsoleAliasRegister("max_companies", "setting max_companies %+");
2070 IConsoleAliasRegister("max_spectators", "setting max_spectators %+");
2071 IConsoleAliasRegister("max_join_time", "setting max_join_time %+");
2072 IConsoleAliasRegister("pause_on_join", "setting pause_on_join %+");
2073 IConsoleAliasRegister("autoclean_companies", "setting autoclean_companies %+");
2074 IConsoleAliasRegister("autoclean_protected", "setting autoclean_protected %+");
2075 IConsoleAliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2076 IConsoleAliasRegister("restart_game_year", "setting restart_game_year %+");
2077 IConsoleAliasRegister("min_players", "setting min_active_clients %+");
2078 IConsoleAliasRegister("reload_cfg", "setting reload_cfg %+");
2079 #endif /* ENABLE_NETWORK */
2081 /* debugging stuff */
2082 #ifdef _DEBUG
2083 IConsoleDebugLibRegister();
2084 #endif
2085 IConsoleCmdRegister("dump_command_log", ConDumpCommandLog, nullptr);
2086 IConsoleCmdRegister("check_caches", ConCheckCaches, nullptr);
2088 /* NewGRF development stuff */
2089 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload, ConHookNewGRFDeveloperTool);