Chunnel: Adjust z position of vehicles in chunnels to go "under" the water.
[openttd-joker.git] / src / console_cmds.cpp
bloba67d53e24c835d14e081e446f1b7feee742dd720
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 NULL
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 != NULL) {
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 != NULL) {
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 != NULL) {
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, NULL);
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, '.') == NULL && strchr(argv, ':') == NULL) { // 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 == NULL) {
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) == NULL) {
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 == NULL) {
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 = NULL;
923 const char *company = NULL;
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 != NULL) {
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 != NULL) {
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 == NULL) {
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) != NULL) {
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 == NULL) 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], NULL, 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(NULL);
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 YearMonthDay ymd;
1345 ConvertDateToYMD(_date, &ymd);
1346 IConsolePrintF(CC_DEFAULT, "Date: %d-%d-%d", ymd.day, ymd.month + 1, ymd.year);
1347 return true;
1351 DEF_CONSOLE_CMD(ConAlias)
1353 IConsoleAlias *alias;
1355 if (argc == 0) {
1356 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1357 return true;
1360 if (argc < 3) return false;
1362 alias = IConsoleAliasGet(argv[1]);
1363 if (alias == NULL) {
1364 IConsoleAliasRegister(argv[1], argv[2]);
1365 } else {
1366 free(alias->cmdline);
1367 alias->cmdline = stredup(argv[2]);
1369 return true;
1372 DEF_CONSOLE_CMD(ConScreenShot)
1374 if (argc == 0) {
1375 IConsoleHelp("Create a screenshot of the game. Usage: 'screenshot [big | giant | no_con] [file name]'");
1376 IConsoleHelp("'big' makes a zoomed-in screenshot of the visible area, 'giant' makes a screenshot of the "
1377 "whole map, 'no_con' hides the console to create the screenshot. 'big' or 'giant' "
1378 "screenshots are always drawn without console");
1379 return true;
1382 if (argc > 3) return false;
1384 ScreenshotType type = SC_VIEWPORT;
1385 const char *name = NULL;
1387 if (argc > 1) {
1388 if (strcmp(argv[1], "big") == 0) {
1389 /* screenshot big [filename] */
1390 type = SC_ZOOMEDIN;
1391 if (argc > 2) name = argv[2];
1392 } else if (strcmp(argv[1], "giant") == 0) {
1393 /* screenshot giant [filename] */
1394 type = SC_WORLD;
1395 if (argc > 2) name = argv[2];
1396 } else if (strcmp(argv[1], "no_con") == 0) {
1397 /* screenshot no_con [filename] */
1398 IConsoleClose();
1399 if (argc > 2) name = argv[2];
1400 } else if (argc == 2) {
1401 /* screenshot filename */
1402 name = argv[1];
1403 } else {
1404 /* screenshot argv[1] argv[2] - invalid */
1405 return false;
1409 MakeScreenshot(type, name);
1410 return true;
1413 DEF_CONSOLE_CMD(ConMinimap)
1415 if (argc == 0) {
1416 IConsoleHelp("Create a flat image of the game minimap. Usage: 'minimap [owner] [file name]'");
1417 IConsoleHelp("'owner' uses the tile owner to colour the minimap image, this is the only mode at present");
1418 return true;
1421 const char *name = NULL;
1422 if (argc > 1) {
1423 if (strcmp(argv[1], "owner") != 0) {
1424 /* invalid mode */
1425 return false;
1428 if (argc > 2) {
1429 name = argv[2];
1432 return MakeScreenshot(SC_MINIMAP, name);
1435 DEF_CONSOLE_CMD(ConInfoCmd)
1437 if (argc == 0) {
1438 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1439 return true;
1442 if (argc < 2) return false;
1444 const IConsoleCmd *cmd = IConsoleCmdGet(argv[1]);
1445 if (cmd == NULL) {
1446 IConsoleError("the given command was not found");
1447 return true;
1450 IConsolePrintF(CC_DEFAULT, "command name: %s", cmd->name);
1451 IConsolePrintF(CC_DEFAULT, "command proc: %p", cmd->proc);
1453 if (cmd->hook != NULL) IConsoleWarning("command is hooked");
1455 return true;
1458 DEF_CONSOLE_CMD(ConDebugLevel)
1460 if (argc == 0) {
1461 IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
1462 IConsoleHelp("Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'s");
1463 return true;
1466 if (argc > 2) return false;
1468 if (argc == 1) {
1469 IConsolePrintF(CC_DEFAULT, "Current debug-level: '%s'", GetDebugString());
1470 } else {
1471 SetDebugString(argv[1]);
1474 return true;
1477 DEF_CONSOLE_CMD(ConExit)
1479 if (argc == 0) {
1480 IConsoleHelp("Exit the game. Usage: 'exit'");
1481 return true;
1484 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
1486 _exit_game = true;
1487 return true;
1490 DEF_CONSOLE_CMD(ConPart)
1492 if (argc == 0) {
1493 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1494 return true;
1497 if (_game_mode != GM_NORMAL) return false;
1499 _switch_mode = SM_MENU;
1500 return true;
1503 DEF_CONSOLE_CMD(ConHelp)
1505 if (argc == 2) {
1506 const IConsoleCmd *cmd;
1507 const IConsoleAlias *alias;
1509 RemoveUnderscores(argv[1]);
1510 cmd = IConsoleCmdGet(argv[1]);
1511 if (cmd != NULL) {
1512 cmd->proc(0, NULL);
1513 return true;
1516 alias = IConsoleAliasGet(argv[1]);
1517 if (alias != NULL) {
1518 cmd = IConsoleCmdGet(alias->cmdline);
1519 if (cmd != NULL) {
1520 cmd->proc(0, NULL);
1521 return true;
1523 IConsolePrintF(CC_ERROR, "ERROR: alias is of special type, please see its execution-line: '%s'", alias->cmdline);
1524 return true;
1527 IConsoleError("command not found");
1528 return true;
1531 IConsolePrint(CC_WARNING, " ---- OpenTTD Console Help ---- ");
1532 IConsolePrint(CC_DEFAULT, " - commands: [command to list all commands: list_cmds]");
1533 IConsolePrint(CC_DEFAULT, " call commands with '<command> <arg2> <arg3>...'");
1534 IConsolePrint(CC_DEFAULT, " - to assign strings, or use them as arguments, enclose it within quotes");
1535 IConsolePrint(CC_DEFAULT, " like this: '<command> \"string argument with spaces\"'");
1536 IConsolePrint(CC_DEFAULT, " - use 'help <command>' to get specific information");
1537 IConsolePrint(CC_DEFAULT, " - scroll console output with shift + (up | down | pageup | pagedown)");
1538 IConsolePrint(CC_DEFAULT, " - scroll console input history with the up or down arrows");
1539 IConsolePrint(CC_DEFAULT, "");
1540 return true;
1543 DEF_CONSOLE_CMD(ConListCommands)
1545 if (argc == 0) {
1546 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1547 return true;
1550 for (const IConsoleCmd *cmd = _iconsole_cmds; cmd != NULL; cmd = cmd->next) {
1551 if (argv[1] == NULL || strstr(cmd->name, argv[1]) != NULL) {
1552 if (cmd->hook == NULL || cmd->hook(false) != CHR_HIDE) IConsolePrintF(CC_DEFAULT, "%s", cmd->name);
1556 return true;
1559 DEF_CONSOLE_CMD(ConListAliases)
1561 if (argc == 0) {
1562 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1563 return true;
1566 for (const IConsoleAlias *alias = _iconsole_aliases; alias != NULL; alias = alias->next) {
1567 if (argv[1] == NULL || strstr(alias->name, argv[1]) != NULL) {
1568 IConsolePrintF(CC_DEFAULT, "%s => %s", alias->name, alias->cmdline);
1572 return true;
1575 DEF_CONSOLE_CMD(ConCompanies)
1577 if (argc == 0) {
1578 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1579 return true;
1582 Company *c;
1583 FOR_ALL_COMPANIES(c) {
1584 /* Grab the company name */
1585 char company_name[512];
1586 SetDParam(0, c->index);
1587 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1589 const char *password_state = "";
1590 if (c->is_ai) {
1591 password_state = "AI";
1593 #ifdef ENABLE_NETWORK
1594 else if (_network_server) {
1595 password_state = StrEmpty(_network_company_states[c->index].password) ? "unprotected" : "protected";
1597 #endif
1599 char colour[512];
1600 GetString(colour, STR_COLOUR_DARK_BLUE + _company_colours[c->index], lastof(colour));
1601 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",
1602 c->index + 1, colour, company_name,
1603 c->inaugurated_year, (int64)c->money, (int64)c->current_loan, (int64)CalculateCompanyValue(c),
1604 c->group_all[VEH_TRAIN].num_vehicle,
1605 c->group_all[VEH_ROAD].num_vehicle,
1606 c->group_all[VEH_AIRCRAFT].num_vehicle,
1607 c->group_all[VEH_SHIP].num_vehicle,
1608 password_state);
1611 return true;
1614 #ifdef ENABLE_NETWORK
1616 DEF_CONSOLE_CMD(ConSay)
1618 if (argc == 0) {
1619 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1620 return true;
1623 if (argc != 2) return false;
1625 if (!_network_server) {
1626 NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
1627 } else {
1628 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1629 NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin);
1632 return true;
1635 DEF_CONSOLE_CMD(ConSayCompany)
1637 if (argc == 0) {
1638 IConsoleHelp("Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'");
1639 IConsoleHelp("CompanyNo is the company that plays as company <companyno>, 1 through max_companies");
1640 return true;
1643 if (argc != 3) return false;
1645 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1646 if (!Company::IsValidID(company_id)) {
1647 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1648 return true;
1651 if (!_network_server) {
1652 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]);
1653 } else {
1654 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1655 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2], CLIENT_ID_SERVER, from_admin);
1658 return true;
1661 DEF_CONSOLE_CMD(ConSayClient)
1663 if (argc == 0) {
1664 IConsoleHelp("Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'");
1665 IConsoleHelp("For client-id's, see the command 'clients'");
1666 return true;
1669 if (argc != 3) return false;
1671 if (!_network_server) {
1672 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
1673 } else {
1674 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1675 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin);
1678 return true;
1681 DEF_CONSOLE_CMD(ConCompanyPassword)
1683 if (argc == 0) {
1684 const char *helpmsg;
1686 if (_network_dedicated) {
1687 helpmsg = "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\"";
1688 } else if (_network_server) {
1689 helpmsg = "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'";
1690 } else {
1691 helpmsg = "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1694 IConsoleHelp(helpmsg);
1695 IConsoleHelp("Use \"*\" to disable the password.");
1696 return true;
1699 CompanyID company_id;
1700 const char *password;
1701 const char *errormsg;
1703 if (argc == 2) {
1704 company_id = _local_company;
1705 password = argv[1];
1706 errormsg = "You have to own a company to make use of this command.";
1707 } else if (argc == 3 && _network_server) {
1708 company_id = (CompanyID)(atoi(argv[1]) - 1);
1709 password = argv[2];
1710 errormsg = "You have to specify the ID of a valid human controlled company.";
1711 } else {
1712 return false;
1715 if (!Company::IsValidHumanID(company_id)) {
1716 IConsoleError(errormsg);
1717 return false;
1720 password = NetworkChangeCompanyPassword(company_id, password);
1722 if (StrEmpty(password)) {
1723 IConsolePrintF(CC_WARNING, "Company password cleared");
1724 } else {
1725 IConsolePrintF(CC_WARNING, "Company password changed to: %s", password);
1728 return true;
1731 /* Content downloading only is available with ZLIB */
1732 #if defined(WITH_ZLIB)
1733 #include "network/network_content.h"
1735 /** Resolve a string to a content type. */
1736 static ContentType StringToContentType(const char *str)
1738 static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1739 for (uint i = 1 /* there is no type 0 */; i < lengthof(inv_lookup); i++) {
1740 if (strcasecmp(str, inv_lookup[i]) == 0) return (ContentType)i;
1742 return CONTENT_TYPE_END;
1745 /** Asynchronous callback */
1746 struct ConsoleContentCallback : public ContentCallback {
1747 void OnConnect(bool success)
1749 IConsolePrintF(CC_DEFAULT, "Content server connection %s", success ? "established" : "failed");
1752 void OnDisconnect()
1754 IConsolePrintF(CC_DEFAULT, "Content server connection closed");
1757 void OnDownloadComplete(ContentID cid)
1759 IConsolePrintF(CC_DEFAULT, "Completed download of %d", cid);
1764 * Outputs content state information to console
1765 * @param ci the content info
1767 static void OutputContentState(const ContentInfo *const ci)
1769 static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1770 assert_compile(lengthof(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN);
1771 static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1772 static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR };
1774 char buf[sizeof(ci->md5sum) * 2 + 1];
1775 md5sumToString(buf, lastof(buf), ci->md5sum);
1776 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);
1779 DEF_CONSOLE_CMD(ConContent)
1781 static ContentCallback *cb = NULL;
1782 if (cb == NULL) {
1783 cb = new ConsoleContentCallback();
1784 _network_content_client.AddCallback(cb);
1787 if (argc <= 1) {
1788 IConsoleHelp("Query, select and download content. Usage: 'content update|upgrade|select [all|id]|unselect [all|id]|state [filter]|download'");
1789 IConsoleHelp(" update: get a new list of downloadable content; must be run first");
1790 IConsoleHelp(" upgrade: select all items that are upgrades");
1791 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");
1792 IConsoleHelp(" unselect: unselect a specific item given by its id or 'all' to unselect all");
1793 IConsoleHelp(" state: show the download/select state of all downloadable content. Optionally give a filter string");
1794 IConsoleHelp(" download: download all content you've selected");
1795 return true;
1798 if (strcasecmp(argv[1], "update") == 0) {
1799 _network_content_client.RequestContentList((argc > 2) ? StringToContentType(argv[2]) : CONTENT_TYPE_END);
1800 return true;
1803 if (strcasecmp(argv[1], "upgrade") == 0) {
1804 _network_content_client.SelectUpgrade();
1805 return true;
1808 if (strcasecmp(argv[1], "select") == 0) {
1809 if (argc <= 2) {
1810 /* List selected content */
1811 IConsolePrintF(CC_WHITE, "id, type, state, name");
1812 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1813 if ((*iter)->state != ContentInfo::SELECTED && (*iter)->state != ContentInfo::AUTOSELECTED) continue;
1814 OutputContentState(*iter);
1816 } else if (strcasecmp(argv[2], "all") == 0) {
1817 _network_content_client.SelectAll();
1818 } else {
1819 _network_content_client.Select((ContentID)atoi(argv[2]));
1821 return true;
1824 if (strcasecmp(argv[1], "unselect") == 0) {
1825 if (argc <= 2) {
1826 IConsoleError("You must enter the id.");
1827 return false;
1829 if (strcasecmp(argv[2], "all") == 0) {
1830 _network_content_client.UnselectAll();
1831 } else {
1832 _network_content_client.Unselect((ContentID)atoi(argv[2]));
1834 return true;
1837 if (strcasecmp(argv[1], "state") == 0) {
1838 IConsolePrintF(CC_WHITE, "id, type, state, name");
1839 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1840 if (argc > 2 && strcasestr((*iter)->name, argv[2]) == NULL) continue;
1841 OutputContentState(*iter);
1843 return true;
1846 if (strcasecmp(argv[1], "download") == 0) {
1847 uint files;
1848 uint bytes;
1849 _network_content_client.DownloadSelectedContent(files, bytes);
1850 IConsolePrintF(CC_DEFAULT, "Downloading %d file(s) (%d bytes)", files, bytes);
1851 return true;
1854 return false;
1856 #endif /* defined(WITH_ZLIB) */
1857 #endif /* ENABLE_NETWORK */
1859 DEF_CONSOLE_CMD(ConSetting)
1861 if (argc == 0) {
1862 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1863 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1864 return true;
1867 if (argc == 1 || argc > 3) return false;
1869 if (argc == 2) {
1870 IConsoleGetSetting(argv[1]);
1871 } else {
1872 IConsoleSetSetting(argv[1], argv[2]);
1875 return true;
1878 DEF_CONSOLE_CMD(ConSettingNewgame)
1880 if (argc == 0) {
1881 IConsoleHelp("Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'");
1882 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1883 return true;
1886 if (argc == 1 || argc > 3) return false;
1888 if (argc == 2) {
1889 IConsoleGetSetting(argv[1], true);
1890 } else {
1891 IConsoleSetSetting(argv[1], argv[2], true);
1894 return true;
1897 DEF_CONSOLE_CMD(ConListSettings)
1899 if (argc == 0) {
1900 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1901 return true;
1904 if (argc > 2) return false;
1906 IConsoleListSettings((argc == 2) ? argv[1] : NULL);
1907 return true;
1910 DEF_CONSOLE_CMD(ConGamelogPrint)
1912 GamelogPrintConsole();
1913 return true;
1916 DEF_CONSOLE_CMD(ConNewGRFReload)
1918 if (argc == 0) {
1919 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1920 return true;
1923 ReloadNewGRFData();
1925 extern void PostCheckNewGRFLoadWarnings();
1926 PostCheckNewGRFLoadWarnings();
1927 return true;
1930 DEF_CONSOLE_CMD(ConDumpCommandLog)
1932 if (argc == 0) {
1933 IConsoleHelp("Dump log of recently executed commands.");
1934 return true;
1937 char buffer[32768];
1938 DumpCommandLog(buffer, lastof(buffer));
1939 PrintLineByLine(buffer);
1940 return true;
1943 #ifdef _DEBUG
1944 /******************
1945 * debug commands
1946 ******************/
1948 static void IConsoleDebugLibRegister()
1950 IConsoleCmdRegister("resettile", ConResetTile);
1951 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
1952 IConsoleAliasRegister("dbg_echo2", "echo %!");
1954 #endif
1956 /*******************************
1957 * console command registration
1958 *******************************/
1960 void IConsoleStdLibRegister()
1962 IConsoleCmdRegister("debug_level", ConDebugLevel);
1963 IConsoleCmdRegister("echo", ConEcho);
1964 IConsoleCmdRegister("echoc", ConEchoC);
1965 IConsoleCmdRegister("exec", ConExec);
1966 IConsoleCmdRegister("exit", ConExit);
1967 IConsoleCmdRegister("part", ConPart);
1968 IConsoleCmdRegister("help", ConHelp);
1969 IConsoleCmdRegister("info_cmd", ConInfoCmd);
1970 IConsoleCmdRegister("list_cmds", ConListCommands);
1971 IConsoleCmdRegister("list_aliases", ConListAliases);
1972 IConsoleCmdRegister("newgame", ConNewGame);
1973 IConsoleCmdRegister("restart", ConRestart);
1974 IConsoleCmdRegister("getseed", ConGetSeed);
1975 IConsoleCmdRegister("getdate", ConGetDate);
1976 IConsoleCmdRegister("quit", ConExit);
1977 IConsoleCmdRegister("resetengines", ConResetEngines, ConHookNoNetwork);
1978 IConsoleCmdRegister("reset_enginepool", ConResetEnginePool, ConHookNoNetwork);
1979 IConsoleCmdRegister("return", ConReturn);
1980 IConsoleCmdRegister("screenshot", ConScreenShot);
1981 IConsoleCmdRegister("minimap", ConMinimap);
1982 IConsoleCmdRegister("script", ConScript);
1983 IConsoleCmdRegister("scrollto", ConScrollToTile);
1984 IConsoleCmdRegister("alias", ConAlias);
1985 IConsoleCmdRegister("load", ConLoad);
1986 IConsoleCmdRegister("rm", ConRemove);
1987 IConsoleCmdRegister("save", ConSave);
1988 IConsoleCmdRegister("saveconfig", ConSaveConfig);
1989 IConsoleCmdRegister("ls", ConListFiles);
1990 IConsoleCmdRegister("cd", ConChangeDirectory);
1991 IConsoleCmdRegister("pwd", ConPrintWorkingDirectory);
1992 IConsoleCmdRegister("clear", ConClearBuffer);
1993 IConsoleCmdRegister("setting", ConSetting);
1994 IConsoleCmdRegister("setting_newgame", ConSettingNewgame);
1995 IConsoleCmdRegister("list_settings",ConListSettings);
1996 IConsoleCmdRegister("gamelog", ConGamelogPrint);
1997 IConsoleCmdRegister("rescan_newgrf", ConRescanNewGRF);
1999 IConsoleAliasRegister("dir", "ls");
2000 IConsoleAliasRegister("del", "rm %+");
2001 IConsoleAliasRegister("newmap", "newgame");
2002 IConsoleAliasRegister("patch", "setting %+");
2003 IConsoleAliasRegister("set", "setting %+");
2004 IConsoleAliasRegister("set_newgame", "setting_newgame %+");
2005 IConsoleAliasRegister("list_patches", "list_settings %+");
2006 IConsoleAliasRegister("developer", "setting developer %+");
2008 IConsoleCmdRegister("list_ai_libs", ConListAILibs);
2009 IConsoleCmdRegister("list_ai", ConListAI);
2010 IConsoleCmdRegister("reload_ai", ConReloadAI);
2011 IConsoleCmdRegister("rescan_ai", ConRescanAI);
2012 IConsoleCmdRegister("start_ai", ConStartAI);
2013 IConsoleCmdRegister("stop_ai", ConStopAI);
2015 IConsoleCmdRegister("list_game", ConListGame);
2016 IConsoleCmdRegister("list_game_libs", ConListGameLibs);
2017 IConsoleCmdRegister("rescan_game", ConRescanGame);
2019 IConsoleCmdRegister("companies", ConCompanies);
2020 IConsoleAliasRegister("players", "companies");
2022 /* networking functions */
2023 #ifdef ENABLE_NETWORK
2024 /* Content downloading is only available with ZLIB */
2025 #if defined(WITH_ZLIB)
2026 IConsoleCmdRegister("content", ConContent);
2027 #endif /* defined(WITH_ZLIB) */
2029 /*** Networking commands ***/
2030 IConsoleCmdRegister("say", ConSay, ConHookNeedNetwork);
2031 IConsoleCmdRegister("say_company", ConSayCompany, ConHookNeedNetwork);
2032 IConsoleAliasRegister("say_player", "say_company %+");
2033 IConsoleCmdRegister("say_client", ConSayClient, ConHookNeedNetwork);
2035 IConsoleCmdRegister("connect", ConNetworkConnect, ConHookClientOnly);
2036 IConsoleCmdRegister("clients", ConNetworkClients, ConHookNeedNetwork);
2037 IConsoleCmdRegister("status", ConStatus, ConHookServerOnly);
2038 IConsoleCmdRegister("server_info", ConServerInfo, ConHookServerOnly);
2039 IConsoleAliasRegister("info", "server_info");
2040 IConsoleCmdRegister("reconnect", ConNetworkReconnect, ConHookClientOnly);
2041 IConsoleCmdRegister("rcon", ConRcon, ConHookNeedNetwork);
2043 IConsoleCmdRegister("join", ConJoinCompany, ConHookNeedNetwork);
2044 IConsoleAliasRegister("spectate", "join 255");
2045 IConsoleCmdRegister("move", ConMoveClient, ConHookServerOnly);
2046 IConsoleCmdRegister("reset_company", ConResetCompany, ConHookServerOnly);
2047 IConsoleAliasRegister("clean_company", "reset_company %A");
2048 IConsoleCmdRegister("client_name", ConClientNickChange, ConHookServerOnly);
2049 IConsoleCmdRegister("kick", ConKick, ConHookServerOnly);
2050 IConsoleCmdRegister("ban", ConBan, ConHookServerOnly);
2051 IConsoleCmdRegister("unban", ConUnBan, ConHookServerOnly);
2052 IConsoleCmdRegister("banlist", ConBanList, ConHookServerOnly);
2054 IConsoleCmdRegister("pause", ConPauseGame, ConHookServerOnly);
2055 IConsoleCmdRegister("unpause", ConUnpauseGame, ConHookServerOnly);
2057 IConsoleCmdRegister("company_pw", ConCompanyPassword, ConHookNeedNetwork);
2058 IConsoleAliasRegister("company_password", "company_pw %+");
2060 IConsoleAliasRegister("net_frame_freq", "setting frame_freq %+");
2061 IConsoleAliasRegister("net_sync_freq", "setting sync_freq %+");
2062 IConsoleAliasRegister("server_pw", "setting server_password %+");
2063 IConsoleAliasRegister("server_password", "setting server_password %+");
2064 IConsoleAliasRegister("rcon_pw", "setting rcon_password %+");
2065 IConsoleAliasRegister("rcon_password", "setting rcon_password %+");
2066 IConsoleAliasRegister("name", "setting client_name %+");
2067 IConsoleAliasRegister("server_name", "setting server_name %+");
2068 IConsoleAliasRegister("server_port", "setting server_port %+");
2069 IConsoleAliasRegister("server_advertise", "setting server_advertise %+");
2070 IConsoleAliasRegister("max_clients", "setting max_clients %+");
2071 IConsoleAliasRegister("max_companies", "setting max_companies %+");
2072 IConsoleAliasRegister("max_spectators", "setting max_spectators %+");
2073 IConsoleAliasRegister("max_join_time", "setting max_join_time %+");
2074 IConsoleAliasRegister("pause_on_join", "setting pause_on_join %+");
2075 IConsoleAliasRegister("autoclean_companies", "setting autoclean_companies %+");
2076 IConsoleAliasRegister("autoclean_protected", "setting autoclean_protected %+");
2077 IConsoleAliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2078 IConsoleAliasRegister("restart_game_year", "setting restart_game_year %+");
2079 IConsoleAliasRegister("min_players", "setting min_active_clients %+");
2080 IConsoleAliasRegister("reload_cfg", "setting reload_cfg %+");
2081 #endif /* ENABLE_NETWORK */
2083 /* debugging stuff */
2084 #ifdef _DEBUG
2085 IConsoleDebugLibRegister();
2086 #endif
2087 IConsoleCmdRegister("dump_command_log", ConDumpCommandLog, nullptr);
2088 IConsoleCmdRegister("check_caches", ConCheckCaches, nullptr);
2090 /* NewGRF development stuff */
2091 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload, ConHookNewGRFDeveloperTool);