Translations update
[openttd/fttd.git] / src / console_cmds.cpp
blobcf875dc061e5c9332e9c7fad1a52365e08d86496
1 /* $Id$ */
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 "string.h"
15 #include "debug.h"
16 #include "engine_func.h"
17 #include "landscape.h"
18 #include "saveload/saveload.h"
19 #include "network/network.h"
20 #include "network/network_func.h"
21 #include "network/network_base.h"
22 #include "network/network_admin.h"
23 #include "network/network_client.h"
24 #include "command_func.h"
25 #include "settings_func.h"
26 #include "fios.h"
27 #include "fileio_func.h"
28 #include "screenshot.h"
29 #include "genworld.h"
30 #include "strings_func.h"
31 #include "viewport_func.h"
32 #include "window_func.h"
33 #include "date_func.h"
34 #include "company_func.h"
35 #include "gamelog.h"
36 #include "ai/ai.hpp"
37 #include "ai/ai_config.hpp"
38 #include "newgrf.h"
39 #include "console_func.h"
40 #include "engine_base.h"
41 #include "game/game.hpp"
42 #include "table/strings.h"
44 /* scriptfile handling */
45 static bool _script_running; ///< Script is running (used to abort execution when #ConReturn is encountered).
47 /** File list storage for the console, for caching the last 'ls' command. */
48 class ConsoleFileList : public FileList {
49 public:
50 ConsoleFileList() : FileList()
52 this->file_list_valid = false;
55 /** Declare the file storage cache as being invalid, also clears all stored files. */
56 void InvalidateFileList()
58 this->Clear();
59 this->file_list_valid = false;
62 /**
63 * (Re-)validate the file storage cache. Only makes a change if the storage was invalid, or if \a force_reload.
64 * @param Always reload the file storage cache.
66 void ValidateFileList(bool force_reload = false)
68 if (force_reload || !this->file_list_valid) {
69 this->BuildFileList(FT_SAVEGAME, SLO_LOAD);
70 this->file_list_valid = true;
74 bool file_list_valid; ///< If set, the file list is valid.
77 static ConsoleFileList _console_file_list; ///< File storage cache for the console.
79 /* console command defines */
80 #define DEF_CONSOLE_CMD(function) static bool function(byte argc, char *argv[])
81 #define DEF_CONSOLE_HOOK(function) static ConsoleHookResult function(bool echo)
84 /****************
85 * command hooks
86 ****************/
88 #ifdef ENABLE_NETWORK
90 /**
91 * Check network availability and inform in console about failure of detection.
92 * @return Network availability.
94 static inline bool NetworkAvailable(bool echo)
96 if (!_network_available) {
97 if (echo) IConsoleError("You cannot use this command because there is no network available.");
98 return false;
100 return true;
104 * Check whether we are a server.
105 * @return Are we a server? True when yes, false otherwise.
107 DEF_CONSOLE_HOOK(ConHookServerOnly)
109 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
111 if (!_network_server) {
112 if (echo) IConsoleError("This command is only available to a network server.");
113 return CHR_DISALLOW;
115 return CHR_ALLOW;
119 * Check whether we are a client in a network game.
120 * @return Are we a client in a network game? True when yes, false otherwise.
122 DEF_CONSOLE_HOOK(ConHookClientOnly)
124 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
126 if (_network_server) {
127 if (echo) IConsoleError("This command is not available to a network server.");
128 return CHR_DISALLOW;
130 return CHR_ALLOW;
134 * Check whether we are in a multiplayer game.
135 * @return True when we are client or server in a network game.
137 DEF_CONSOLE_HOOK(ConHookNeedNetwork)
139 if (!NetworkAvailable(echo)) return CHR_DISALLOW;
141 if (!_networking || (!_network_server && !MyClient::IsConnected())) {
142 if (echo) IConsoleError("Not connected. This command is only available in multiplayer.");
143 return CHR_DISALLOW;
145 return CHR_ALLOW;
149 * Check whether we are in single player mode.
150 * @return True when no network is active.
152 DEF_CONSOLE_HOOK(ConHookNoNetwork)
154 if (_networking) {
155 if (echo) IConsoleError("This command is forbidden in multiplayer.");
156 return CHR_DISALLOW;
158 return CHR_ALLOW;
161 #else
162 # define ConHookNoNetwork NULL
163 #endif /* ENABLE_NETWORK */
165 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool)
167 if (_settings_client.gui.newgrf_developer_tools) {
168 if (_game_mode == GM_MENU) {
169 if (echo) IConsoleError("This command is only available in game and editor.");
170 return CHR_DISALLOW;
172 #ifdef ENABLE_NETWORK
173 return ConHookNoNetwork(echo);
174 #else
175 return CHR_ALLOW;
176 #endif
178 return CHR_HIDE;
182 * Show help for the console.
183 * @param str String to print in the console.
185 static void IConsoleHelp(const char *str)
187 IConsolePrintF(CC_WARNING, "- %s", str);
191 * Reset status of all engines.
192 * @return Will always succeed.
194 DEF_CONSOLE_CMD(ConResetEngines)
196 if (argc == 0) {
197 IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'");
198 return true;
201 StartupEngines();
202 return true;
206 * Reset status of the engine pool.
207 * @return Will always return true.
208 * @note Resetting the pool only succeeds when there are no vehicles ingame.
210 DEF_CONSOLE_CMD(ConResetEnginePool)
212 if (argc == 0) {
213 IConsoleHelp("Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
214 return true;
217 if (_game_mode == GM_MENU) {
218 IConsoleError("This command is only available in game and editor.");
219 return true;
222 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
223 IConsoleError("This can only be done when there are no vehicles in the game.");
224 return true;
227 return true;
230 #ifdef _DEBUG
232 * Reset a tile to bare land in debug mode.
233 * param tile number.
234 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
236 DEF_CONSOLE_CMD(ConResetTile)
238 if (argc == 0) {
239 IConsoleHelp("Reset a tile to bare land. Usage: 'resettile <tile>'");
240 IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)");
241 return true;
244 if (argc == 2) {
245 uint32 result;
246 if (GetArgumentInteger(&result, argv[1])) {
247 DoClearSquare((TileIndex)result);
248 return true;
252 return false;
254 #endif /* _DEBUG */
257 * Scroll to a tile on the map.
258 * @param arg1 tile tile number or tile x coordinate.
259 * @param arg2 optionally tile y coordinate.
260 * @note When only one argument is given it is intepreted as the tile number.
261 * When two arguments are given, they are interpreted as the tile's x
262 * and y coordinates.
263 * @return True when either console help was shown or a proper amount of parameters given.
265 DEF_CONSOLE_CMD(ConScrollToTile)
267 switch (argc) {
268 case 0:
269 IConsoleHelp("Center the screen on a given tile.");
270 IConsoleHelp("Usage: 'scrollto <tile>' or 'scrollto <x> <y>'");
271 IConsoleHelp("Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
272 return true;
274 case 2: {
275 uint32 result;
276 if (GetArgumentInteger(&result, argv[1])) {
277 if (result >= MapSize()) {
278 IConsolePrint(CC_ERROR, "Tile does not exist");
279 return true;
281 ScrollMainWindowToTile((TileIndex)result);
282 return true;
284 break;
287 case 3: {
288 uint32 x, y;
289 if (GetArgumentInteger(&x, argv[1]) && GetArgumentInteger(&y, argv[2])) {
290 if (x >= MapSizeX() || y >= MapSizeY()) {
291 IConsolePrint(CC_ERROR, "Tile does not exist");
292 return true;
294 ScrollMainWindowToTile(TileXY(x, y));
295 return true;
297 break;
301 return false;
305 * Save the map to a file.
306 * @param filename the filename to save the map to.
307 * @return True when help was displayed or the file attempted to be saved.
309 DEF_CONSOLE_CMD(ConSave)
311 if (argc == 0) {
312 IConsoleHelp("Save the current game. Usage: 'save <filename>'");
313 return true;
316 if (argc == 2) {
317 char *filename = str_fmt("%s.sav", argv[1]);
318 IConsolePrint(CC_DEFAULT, "Saving map...");
320 if (!SaveGame(filename, SAVE_DIR)) {
321 IConsolePrint(CC_ERROR, "Saving map failed");
322 } else {
323 IConsolePrintF(CC_DEFAULT, "Map successfully saved to %s", filename);
325 free(filename);
326 return true;
329 return false;
333 * Explicitly save the configuration.
334 * @return True.
336 DEF_CONSOLE_CMD(ConSaveConfig)
338 if (argc == 0) {
339 IConsoleHelp("Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
340 IConsoleHelp("It does not save the configuration of the current game to the configuration file.");
341 return true;
344 SaveToConfig();
345 IConsolePrint(CC_DEFAULT, "Saved config.");
346 return true;
349 DEF_CONSOLE_CMD(ConLoad)
351 if (argc == 0) {
352 IConsoleHelp("Load a game by name or index. Usage: 'load <file | number>'");
353 return true;
356 if (argc != 2) return false;
358 const char *file = argv[1];
359 _console_file_list.ValidateFileList();
360 const FiosItem *item = _console_file_list.FindItem(file);
361 if (item != NULL) {
362 if (GetAbstractFileType(item->type) == FT_SAVEGAME) {
363 _switch_mode = SM_LOAD_GAME;
364 _file_to_saveload.SetMode(item->type);
365 _file_to_saveload.SetName(FiosBrowseTo(item));
366 _file_to_saveload.SetTitle(item->title);
367 } else {
368 IConsolePrintF(CC_ERROR, "%s: Not a savegame.", file);
370 } else {
371 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
374 return true;
378 DEF_CONSOLE_CMD(ConRemove)
380 if (argc == 0) {
381 IConsoleHelp("Remove a savegame by name or index. Usage: 'rm <file | number>'");
382 return true;
385 if (argc != 2) return false;
387 const char *file = argv[1];
388 _console_file_list.ValidateFileList();
389 const FiosItem *item = _console_file_list.FindItem(file);
390 if (item != NULL) {
391 if (!FiosDelete(item->name)) {
392 IConsolePrintF(CC_ERROR, "%s: Failed to delete file", file);
394 } else {
395 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
398 _console_file_list.InvalidateFileList();
399 return true;
403 /* List all the files in the current dir via console */
404 DEF_CONSOLE_CMD(ConListFiles)
406 if (argc == 0) {
407 IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'");
408 return true;
411 _console_file_list.ValidateFileList(true);
412 for (uint i = 0; i < _console_file_list.Length(); i++) {
413 IConsolePrintF(CC_DEFAULT, "%d) %s", i, _console_file_list[i].title);
416 return true;
419 /* Change the dir via console */
420 DEF_CONSOLE_CMD(ConChangeDirectory)
422 if (argc == 0) {
423 IConsoleHelp("Change the dir via console. Usage: 'cd <directory | number>'");
424 return true;
427 if (argc != 2) return false;
429 const char *file = argv[1];
430 _console_file_list.ValidateFileList(true);
431 const FiosItem *item = _console_file_list.FindItem(file);
432 if (item != NULL) {
433 switch (item->type) {
434 case FIOS_TYPE_DIR: case FIOS_TYPE_DRIVE: case FIOS_TYPE_PARENT:
435 FiosBrowseTo(item);
436 break;
437 default: IConsolePrintF(CC_ERROR, "%s: Not a directory.", file);
439 } else {
440 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
443 _console_file_list.InvalidateFileList();
444 return true;
447 DEF_CONSOLE_CMD(ConPrintWorkingDirectory)
449 if (argc == 0) {
450 IConsoleHelp("Print out the current working directory. Usage: 'pwd'");
451 return true;
454 /* XXX - Workaround for broken file handling */
455 _console_file_list.ValidateFileList(true);
456 _console_file_list.InvalidateFileList();
458 IConsolePrint (CC_DEFAULT, FiosGetPath());
459 return true;
462 DEF_CONSOLE_CMD(ConClearBuffer)
464 if (argc == 0) {
465 IConsoleHelp("Clear the console buffer. Usage: 'clear'");
466 return true;
469 IConsoleClearBuffer();
470 SetWindowDirty(WC_CONSOLE, 0);
471 return true;
475 /**********************************
476 * Network Core Console Commands
477 **********************************/
478 #ifdef ENABLE_NETWORK
480 static bool ConKickOrBan(const char *argv, bool ban)
482 uint n;
484 if (strchr(argv, '.') == NULL && strchr(argv, ':') == NULL) { // banning with ID
485 ClientID client_id = (ClientID)atoi(argv);
487 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
488 * kicking frees closes and subsequently free the connection related instances, which we
489 * would be reading from and writing to after returning. So we would read or write data
490 * from freed memory up till the segfault triggers. */
491 if (client_id == CLIENT_ID_SERVER || client_id == _redirect_console_to_client) {
492 IConsolePrintF(CC_ERROR, "ERROR: Silly boy, you can not %s yourself!", ban ? "ban" : "kick");
493 return true;
496 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
497 if (ci == NULL) {
498 IConsoleError("Invalid client");
499 return true;
502 if (!ban) {
503 /* Kick only this client, not all clients with that IP */
504 NetworkServerKickClient(client_id);
505 return true;
508 /* When banning, kick+ban all clients with that IP */
509 n = NetworkServerKickOrBanIP(client_id, ban);
510 } else {
511 n = NetworkServerKickOrBanIP(argv, ban);
514 if (n == 0) {
515 IConsolePrint(CC_DEFAULT, ban ? "Client not online, address added to banlist" : "Client not found");
516 } else {
517 IConsolePrintF(CC_DEFAULT, "%sed %u client(s)", ban ? "Bann" : "Kick", n);
520 return true;
523 DEF_CONSOLE_CMD(ConKick)
525 if (argc == 0) {
526 IConsoleHelp("Kick a client from a network game. Usage: 'kick <ip | client-id>'");
527 IConsoleHelp("For client-id's, see the command 'clients'");
528 return true;
531 if (argc != 2) return false;
533 return ConKickOrBan(argv[1], false);
536 DEF_CONSOLE_CMD(ConBan)
538 if (argc == 0) {
539 IConsoleHelp("Ban a client from a network game. Usage: 'ban <ip | client-id>'");
540 IConsoleHelp("For client-id's, see the command 'clients'");
541 IConsoleHelp("If the client is no longer online, you can still ban his/her IP");
542 return true;
545 if (argc != 2) return false;
547 return ConKickOrBan(argv[1], true);
550 DEF_CONSOLE_CMD(ConUnBan)
553 if (argc == 0) {
554 IConsoleHelp("Unban a client from a network game. Usage: 'unban <ip | client-id>'");
555 IConsoleHelp("For a list of banned IP's, see the command 'banlist'");
556 return true;
559 if (argc != 2) return false;
561 uint index = (strchr(argv[1], '.') == NULL) ? atoi(argv[1]) : 0;
562 index--;
563 uint i = 0;
565 for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) {
566 if (strcmp(_network_ban_list[i], argv[1]) == 0 || index == i) {
567 free(_network_ban_list[i]);
568 _network_ban_list.Erase(iter);
569 IConsolePrint(CC_DEFAULT, "IP unbanned.");
570 return true;
574 IConsolePrint(CC_DEFAULT, "IP not in ban-list.");
575 return true;
578 DEF_CONSOLE_CMD(ConBanList)
580 if (argc == 0) {
581 IConsoleHelp("List the IP's of banned clients: Usage 'banlist'");
582 return true;
585 IConsolePrint(CC_DEFAULT, "Banlist: ");
587 uint i = 1;
588 for (char **iter = _network_ban_list.Begin(); iter != _network_ban_list.End(); iter++, i++) {
589 IConsolePrintF(CC_DEFAULT, " %d) %s", i, *iter);
592 return true;
595 DEF_CONSOLE_CMD(ConPauseGame)
597 if (argc == 0) {
598 IConsoleHelp("Pause a network game. Usage: 'pause'");
599 return true;
602 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
603 DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
604 if (!_networking) IConsolePrint(CC_DEFAULT, "Game paused.");
605 } else {
606 IConsolePrint(CC_DEFAULT, "Game is already paused.");
609 return true;
612 DEF_CONSOLE_CMD(ConUnpauseGame)
614 if (argc == 0) {
615 IConsoleHelp("Unpause a network game. Usage: 'unpause'");
616 return true;
619 if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) {
620 DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
621 if (!_networking) IConsolePrint(CC_DEFAULT, "Game unpaused.");
622 } else if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED) {
623 IConsolePrint(CC_DEFAULT, "Game is in error state and cannot be unpaused via console.");
624 } else if (_pause_mode != PM_UNPAUSED) {
625 IConsolePrint(CC_DEFAULT, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
626 } else {
627 IConsolePrint(CC_DEFAULT, "Game is already unpaused.");
630 return true;
633 DEF_CONSOLE_CMD(ConRcon)
635 if (argc == 0) {
636 IConsoleHelp("Remote control the server from another client. Usage: 'rcon <password> <command>'");
637 IConsoleHelp("Remember to enclose the command in quotes, otherwise only the first parameter is sent");
638 return true;
641 if (argc < 3) return false;
643 if (_network_server) {
644 IConsoleCmdExec(argv[2]);
645 } else {
646 NetworkClientSendRcon(argv[1], argv[2]);
648 return true;
651 DEF_CONSOLE_CMD(ConStatus)
653 if (argc == 0) {
654 IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
655 return true;
658 NetworkServerShowStatusToConsole();
659 return true;
662 DEF_CONSOLE_CMD(ConServerInfo)
664 if (argc == 0) {
665 IConsoleHelp("List current and maximum client/company limits. Usage 'server_info'");
666 IConsoleHelp("You can change these values by modifying settings 'network.max_clients', 'network.max_companies' and 'network.max_spectators'");
667 return true;
670 IConsolePrintF(CC_DEFAULT, "Current/maximum clients: %2d/%2d", _network_game_info.clients_on, _settings_client.network.max_clients);
671 IConsolePrintF(CC_DEFAULT, "Current/maximum companies: %2d/%2d", (int)Company::GetNumItems(), _settings_client.network.max_companies);
672 IConsolePrintF(CC_DEFAULT, "Current/maximum spectators: %2d/%2d", NetworkSpectatorCount(), _settings_client.network.max_spectators);
674 return true;
677 DEF_CONSOLE_CMD(ConClientNickChange)
679 if (argc != 3) {
680 IConsoleHelp("Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'");
681 IConsoleHelp("For client-id's, see the command 'clients'");
682 return true;
685 ClientID client_id = (ClientID)atoi(argv[1]);
687 if (client_id == CLIENT_ID_SERVER) {
688 IConsoleError("Please use the command 'name' to change your own name!");
689 return true;
692 if (NetworkClientInfo::GetByClientID(client_id) == NULL) {
693 IConsoleError("Invalid client");
694 return true;
697 if (!NetworkServerChangeClientName(client_id, argv[2])) {
698 IConsoleError("Cannot give a client a duplicate name");
701 return true;
704 DEF_CONSOLE_CMD(ConJoinCompany)
706 if (argc < 2) {
707 IConsoleHelp("Request joining another company. Usage: join <company-id> [<password>]");
708 IConsoleHelp("For valid company-id see company list, use 255 for spectator");
709 return true;
712 CompanyID company_id = (CompanyID)(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1]));
714 /* Check we have a valid company id! */
715 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
716 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
717 return true;
720 if (NetworkClientInfo::GetByClientID(_network_own_client_id)->client_playas == company_id) {
721 IConsoleError("You are already there!");
722 return true;
725 if (company_id == COMPANY_SPECTATOR && NetworkMaxSpectatorsReached()) {
726 IConsoleError("Cannot join spectators, maximum number of spectators reached.");
727 return true;
730 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
731 IConsoleError("Cannot join AI company.");
732 return true;
735 /* Check if the company requires a password */
736 if (NetworkCompanyIsPassworded(company_id) && argc < 3) {
737 IConsolePrintF(CC_ERROR, "Company %d requires a password to join.", company_id + 1);
738 return true;
741 /* non-dedicated server may just do the move! */
742 if (_network_server) {
743 NetworkServerDoMove(CLIENT_ID_SERVER, company_id);
744 } else {
745 NetworkClientRequestMove(company_id, NetworkCompanyIsPassworded(company_id) ? argv[2] : "");
748 return true;
751 DEF_CONSOLE_CMD(ConMoveClient)
753 if (argc < 3) {
754 IConsoleHelp("Move a client to another company. Usage: move <client-id> <company-id>");
755 IConsoleHelp("For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators");
756 return true;
759 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID((ClientID)atoi(argv[1]));
760 CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2]));
762 /* check the client exists */
763 if (ci == NULL) {
764 IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
765 return true;
768 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
769 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
770 return true;
773 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
774 IConsoleError("You cannot move clients to AI companies.");
775 return true;
778 if (ci->client_id == CLIENT_ID_SERVER && _network_dedicated) {
779 IConsoleError("Silly boy, you cannot move the server!");
780 return true;
783 if (ci->client_playas == company_id) {
784 IConsoleError("You cannot move someone to where he/she already is!");
785 return true;
788 /* we are the server, so force the update */
789 NetworkServerDoMove(ci->client_id, company_id);
791 return true;
794 DEF_CONSOLE_CMD(ConResetCompany)
796 if (argc == 0) {
797 IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company <company-id>'");
798 IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
799 return true;
802 if (argc != 2) return false;
804 CompanyID index = (CompanyID)(atoi(argv[1]) - 1);
806 /* Check valid range */
807 if (!Company::IsValidID(index)) {
808 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
809 return true;
812 if (!Company::IsHumanID(index)) {
813 IConsoleError("Company is owned by an AI.");
814 return true;
817 if (NetworkCompanyHasClients(index)) {
818 IConsoleError("Cannot remove company: a client is connected to that company.");
819 return false;
821 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
822 if (ci->client_playas == index) {
823 IConsoleError("Cannot remove company: the server is connected to that company.");
824 return true;
827 /* It is safe to remove this company */
828 DoCommandP(0, 2 | index << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
829 IConsolePrint(CC_DEFAULT, "Company deleted.");
831 return true;
834 DEF_CONSOLE_CMD(ConNetworkClients)
836 if (argc == 0) {
837 IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'");
838 return true;
841 NetworkPrintClients();
843 return true;
846 DEF_CONSOLE_CMD(ConNetworkReconnect)
848 if (argc == 0) {
849 IConsoleHelp("Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'");
850 IConsoleHelp("Company 255 is spectator (default, if not specified), 0 means creating new company.");
851 IConsoleHelp("All others are a certain company with Company 1 being #1");
852 return true;
855 CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR;
856 switch (playas) {
857 case 0: playas = COMPANY_NEW_COMPANY; break;
858 case COMPANY_SPECTATOR: /* nothing to do */ break;
859 default:
860 /* From a user pov 0 is a new company, internally it's different and all
861 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
862 playas--;
863 if (playas < COMPANY_FIRST || playas >= MAX_COMPANIES) return false;
864 break;
867 if (StrEmpty(_settings_client.network.last_host)) {
868 IConsolePrint(CC_DEFAULT, "No server for reconnecting.");
869 return true;
872 /* Don't resolve the address first, just print it directly as it comes from the config file. */
873 IConsolePrintF(CC_DEFAULT, "Reconnecting to %s:%d...", _settings_client.network.last_host, _settings_client.network.last_port);
875 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), playas);
876 return true;
879 DEF_CONSOLE_CMD(ConNetworkConnect)
881 if (argc == 0) {
882 IConsoleHelp("Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'");
883 IConsoleHelp("IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'");
884 IConsoleHelp("Company #255 is spectator all others are a certain company with Company 1 being #1");
885 return true;
888 if (argc < 2) return false;
889 if (_networking) NetworkDisconnect(); // we are in network-mode, first close it!
891 const char *port = NULL;
892 const char *company = NULL;
893 char *ip = argv[1];
894 /* Default settings: default port and new company */
895 uint16 rport = NETWORK_DEFAULT_PORT;
896 CompanyID join_as = COMPANY_NEW_COMPANY;
898 ParseConnectionString(&company, &port, ip);
900 IConsolePrintF(CC_DEFAULT, "Connecting to %s...", ip);
901 if (company != NULL) {
902 join_as = (CompanyID)atoi(company);
903 IConsolePrintF(CC_DEFAULT, " company-no: %d", join_as);
905 /* From a user pov 0 is a new company, internally it's different and all
906 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
907 if (join_as != COMPANY_SPECTATOR) {
908 if (join_as > MAX_COMPANIES) return false;
909 join_as--;
912 if (port != NULL) {
913 rport = atoi(port);
914 IConsolePrintF(CC_DEFAULT, " port: %s", port);
917 NetworkClientConnectGame(NetworkAddress(ip, rport), join_as);
919 return true;
922 #endif /* ENABLE_NETWORK */
924 /*********************************
925 * script file console commands
926 *********************************/
928 DEF_CONSOLE_CMD(ConExec)
930 if (argc == 0) {
931 IConsoleHelp("Execute a local script file. Usage: 'exec <script> <?>'");
932 return true;
935 if (argc < 2) return false;
937 FILE *script_file = FioFOpenFile(argv[1], "r", BASE_DIR);
939 if (script_file == NULL) {
940 if (argc == 2 || atoi(argv[2]) != 0) IConsoleError("script file not found");
941 return true;
944 _script_running = true;
946 char cmdline[ICON_CMDLN_SIZE];
947 while (_script_running && fgets(cmdline, sizeof(cmdline), script_file) != NULL) {
948 /* Remove newline characters from the executing script */
949 for (char *cmdptr = cmdline; *cmdptr != '\0'; cmdptr++) {
950 if (*cmdptr == '\n' || *cmdptr == '\r') {
951 *cmdptr = '\0';
952 break;
955 IConsoleCmdExec(cmdline);
958 if (ferror(script_file)) {
959 IConsoleError("Encountered error while trying to read from script file");
962 _script_running = false;
963 FioFCloseFile(script_file);
964 return true;
967 DEF_CONSOLE_CMD(ConReturn)
969 if (argc == 0) {
970 IConsoleHelp("Stop executing a running script. Usage: 'return'");
971 return true;
974 _script_running = false;
975 return true;
978 /*****************************
979 * default console commands
980 ******************************/
981 extern bool CloseConsoleLogIfActive();
983 DEF_CONSOLE_CMD(ConScript)
985 extern FILE *_iconsole_output_file;
987 if (argc == 0) {
988 IConsoleHelp("Start or stop logging console output to a file. Usage: 'script <filename>'");
989 IConsoleHelp("If filename is omitted, a running log is stopped if it is active");
990 return true;
993 if (!CloseConsoleLogIfActive()) {
994 if (argc < 2) return false;
996 IConsolePrintF(CC_DEFAULT, "file output started to: %s", argv[1]);
997 _iconsole_output_file = fopen(argv[1], "ab");
998 if (_iconsole_output_file == NULL) IConsoleError("could not open file");
1001 return true;
1005 DEF_CONSOLE_CMD(ConEcho)
1007 if (argc == 0) {
1008 IConsoleHelp("Print back the first argument to the console. Usage: 'echo <arg>'");
1009 return true;
1012 if (argc < 2) return false;
1013 IConsolePrint(CC_DEFAULT, argv[1]);
1014 return true;
1017 DEF_CONSOLE_CMD(ConEchoC)
1019 if (argc == 0) {
1020 IConsoleHelp("Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'");
1021 return true;
1024 if (argc < 3) return false;
1025 IConsolePrint((TextColour)Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1), argv[2]);
1026 return true;
1029 DEF_CONSOLE_CMD(ConNewGame)
1031 if (argc == 0) {
1032 IConsoleHelp("Start a new game. Usage: 'newgame [seed]'");
1033 IConsoleHelp("The server can force a new game using 'newgame'; any client joined will rejoin after the server is done generating the new game.");
1034 return true;
1037 StartNewGameWithoutGUI((argc == 2) ? strtoul(argv[1], NULL, 10) : GENERATE_NEW_SEED);
1038 return true;
1041 DEF_CONSOLE_CMD(ConRestart)
1043 if (argc == 0) {
1044 IConsoleHelp("Restart game. Usage: 'restart'");
1045 IConsoleHelp("Restarts a game. It tries to reproduce the exact same map as the game started with.");
1046 IConsoleHelp("However:");
1047 IConsoleHelp(" * restarting games started in another version might create another map due to difference in map generation");
1048 IConsoleHelp(" * restarting games based on scenarios, loaded games or heightmaps will start a new game based on the settings stored in the scenario/savegame");
1049 return true;
1052 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1053 _settings_game.game_creation.map_x = MapLogX();
1054 _settings_game.game_creation.map_y = FindFirstBit(MapSizeY());
1055 _switch_mode = SM_RESTARTGAME;
1056 return true;
1060 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1061 * @param buf The buffer to print.
1063 static void PrintLineByLine (const char *buf)
1065 const char *p;
1066 /* Print output line by line */
1067 while ((p = strchr (buf, '\n')) != NULL) {
1068 int len = p - buf;
1069 IConsolePrintF (CC_DEFAULT, "%.*s", len, buf);
1070 buf = p + 1;
1074 DEF_CONSOLE_CMD(ConListAILibs)
1076 sstring<4096> buf;
1077 AI::GetConsoleLibraryList (&buf);
1079 PrintLineByLine (buf.c_str());
1081 return true;
1084 DEF_CONSOLE_CMD(ConListAI)
1086 sstring<4096> buf;
1087 AI::GetConsoleList (&buf);
1089 PrintLineByLine (buf.c_str());
1091 return true;
1094 DEF_CONSOLE_CMD(ConListGameLibs)
1096 sstring<4096> buf;
1097 Game::GetConsoleLibraryList (&buf);
1099 PrintLineByLine (buf.c_str());
1101 return true;
1104 DEF_CONSOLE_CMD(ConListGame)
1106 sstring<4096> buf;
1107 Game::GetConsoleList (&buf);
1109 PrintLineByLine (buf.c_str());
1111 return true;
1114 DEF_CONSOLE_CMD(ConStartAI)
1116 if (argc == 0 || argc > 3) {
1117 IConsoleHelp("Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'");
1118 IConsoleHelp("Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1119 IConsoleHelp("If <settings> is given, it is parsed and the AI settings are set to that.");
1120 return true;
1123 if (_game_mode != GM_NORMAL) {
1124 IConsoleWarning("AIs can only be managed in a game.");
1125 return true;
1128 if (Company::GetNumItems() == Company::Pool::MAX_SIZE) {
1129 IConsoleWarning("Can't start a new AI (no more free slots).");
1130 return true;
1132 if (_networking && !_network_server) {
1133 IConsoleWarning("Only the server can start a new AI.");
1134 return true;
1136 if (_networking && !_settings_game.ai.ai_in_multiplayer) {
1137 IConsoleWarning("AIs are not allowed in multiplayer by configuration.");
1138 IConsoleWarning("Switch AI -> AI in multiplayer to True.");
1139 return true;
1141 if (!AI::CanStartNew()) {
1142 IConsoleWarning("Can't start a new AI.");
1143 return true;
1146 int n = 0;
1147 Company *c;
1148 /* Find the next free slot */
1149 FOR_ALL_COMPANIES(c) {
1150 if (c->index != n) break;
1151 n++;
1154 AIConfig *config = AIConfig::GetConfig((CompanyID)n);
1155 if (argc >= 2) {
1156 config->Change(argv[1], -1, true);
1157 if (!config->HasScript()) {
1158 IConsoleWarning("Failed to load the specified AI");
1159 return true;
1161 if (argc == 3) {
1162 config->StringToSettings(argv[2]);
1166 /* Start a new AI company */
1167 DoCommandP(0, 1 | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
1169 return true;
1172 DEF_CONSOLE_CMD(ConReloadAI)
1174 if (argc != 2) {
1175 IConsoleHelp("Reload an AI. Usage: 'reload_ai <company-id>'");
1176 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.");
1177 return true;
1180 if (_game_mode != GM_NORMAL) {
1181 IConsoleWarning("AIs can only be managed in a game.");
1182 return true;
1185 if (_networking && !_network_server) {
1186 IConsoleWarning("Only the server can reload an AI.");
1187 return true;
1190 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1191 if (!Company::IsValidID(company_id)) {
1192 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1193 return true;
1196 if (Company::IsHumanID(company_id)) {
1197 IConsoleWarning("Company is not controlled by an AI.");
1198 return true;
1201 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1202 DoCommandP(0, 2 | company_id << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
1203 DoCommandP(0, 1 | company_id << 16, 0, CMD_COMPANY_CTRL);
1204 IConsolePrint(CC_DEFAULT, "AI reloaded.");
1206 return true;
1209 DEF_CONSOLE_CMD(ConStopAI)
1211 if (argc != 2) {
1212 IConsoleHelp("Stop an AI. Usage: 'stop_ai <company-id>'");
1213 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.");
1214 return true;
1217 if (_game_mode != GM_NORMAL) {
1218 IConsoleWarning("AIs can only be managed in a game.");
1219 return true;
1222 if (_networking && !_network_server) {
1223 IConsoleWarning("Only the server can stop an AI.");
1224 return true;
1227 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1228 if (!Company::IsValidID(company_id)) {
1229 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1230 return true;
1233 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1234 IConsoleWarning("Company is not controlled by an AI.");
1235 return true;
1238 /* Now kill the company of the AI. */
1239 DoCommandP(0, 2 | company_id << 16, CRR_MANUAL, CMD_COMPANY_CTRL);
1240 IConsolePrint(CC_DEFAULT, "AI stopped, company deleted.");
1242 return true;
1245 DEF_CONSOLE_CMD(ConRescanAI)
1247 if (argc == 0) {
1248 IConsoleHelp("Rescan the AI dir for scripts. Usage: 'rescan_ai'");
1249 return true;
1252 if (_networking && !_network_server) {
1253 IConsoleWarning("Only the server can rescan the AI dir for scripts.");
1254 return true;
1257 AI::Rescan();
1259 return true;
1262 DEF_CONSOLE_CMD(ConRescanGame)
1264 if (argc == 0) {
1265 IConsoleHelp("Rescan the Game Script dir for scripts. Usage: 'rescan_game'");
1266 return true;
1269 if (_networking && !_network_server) {
1270 IConsoleWarning("Only the server can rescan the Game Script dir for scripts.");
1271 return true;
1274 Game::Rescan();
1276 return true;
1279 DEF_CONSOLE_CMD(ConRescanNewGRF)
1281 if (argc == 0) {
1282 IConsoleHelp("Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'");
1283 return true;
1286 ScanNewGRFFiles(NULL);
1288 return true;
1291 DEF_CONSOLE_CMD(ConGetSeed)
1293 if (argc == 0) {
1294 IConsoleHelp("Returns the seed used to create this game. Usage: 'getseed'");
1295 IConsoleHelp("The seed can be used to reproduce the exact same map as the game started with.");
1296 return true;
1299 IConsolePrintF(CC_DEFAULT, "Generation Seed: %u", _settings_game.game_creation.generation_seed);
1300 return true;
1303 DEF_CONSOLE_CMD(ConGetDate)
1305 if (argc == 0) {
1306 IConsoleHelp("Returns the current date (day-month-year) of the game. Usage: 'getdate'");
1307 return true;
1310 YearMonthDay ymd;
1311 ConvertDateToYMD(_date, &ymd);
1312 IConsolePrintF(CC_DEFAULT, "Date: %d-%d-%d", ymd.day, ymd.month + 1, ymd.year);
1313 return true;
1317 DEF_CONSOLE_CMD(ConAlias)
1319 IConsoleAlias *alias;
1321 if (argc == 0) {
1322 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1323 return true;
1326 if (argc < 3) return false;
1328 alias = IConsoleAliasGet(argv[1]);
1329 if (alias == NULL) {
1330 IConsoleAliasRegister(argv[1], argv[2]);
1331 } else {
1332 free(alias->cmdline);
1333 alias->cmdline = xstrdup(argv[2]);
1335 return true;
1338 DEF_CONSOLE_CMD(ConScreenShot)
1340 if (argc == 0) {
1341 IConsoleHelp("Create a screenshot of the game. Usage: 'screenshot [big | giant | no_con] [file name]'");
1342 IConsoleHelp("'big' makes a zoomed-in screenshot of the visible area, 'giant' makes a screenshot of the "
1343 "whole map, 'no_con' hides the console to create the screenshot. 'big' or 'giant' "
1344 "screenshots are always drawn without console");
1345 return true;
1348 if (argc > 3) return false;
1350 ScreenshotType type = SC_VIEWPORT;
1351 const char *name = NULL;
1353 if (argc > 1) {
1354 if (strcmp(argv[1], "big") == 0) {
1355 /* screenshot big [filename] */
1356 type = SC_ZOOMEDIN;
1357 if (argc > 2) name = argv[2];
1358 } else if (strcmp(argv[1], "giant") == 0) {
1359 /* screenshot giant [filename] */
1360 type = SC_WORLD;
1361 if (argc > 2) name = argv[2];
1362 } else if (strcmp(argv[1], "no_con") == 0) {
1363 /* screenshot no_con [filename] */
1364 IConsoleClose();
1365 if (argc > 2) name = argv[2];
1366 } else if (argc == 2) {
1367 /* screenshot filename */
1368 name = argv[1];
1369 } else {
1370 /* screenshot argv[1] argv[2] - invalid */
1371 return false;
1375 MakeScreenshot(type, name);
1376 return true;
1379 DEF_CONSOLE_CMD(ConInfoCmd)
1381 if (argc == 0) {
1382 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1383 return true;
1386 if (argc < 2) return false;
1388 const IConsoleCmd *cmd = IConsoleCmdGet(argv[1]);
1389 if (cmd == NULL) {
1390 IConsoleError("the given command was not found");
1391 return true;
1394 IConsolePrintF(CC_DEFAULT, "command name: %s", cmd->name);
1395 IConsolePrintF(CC_DEFAULT, "command proc: %p", cmd->proc);
1397 if (cmd->hook != NULL) IConsoleWarning("command is hooked");
1399 return true;
1402 DEF_CONSOLE_CMD(ConDebugLevel)
1404 if (argc == 0) {
1405 IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
1406 IConsoleHelp("Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'s");
1407 return true;
1410 if (argc > 2) return false;
1412 if (argc == 1) {
1413 IConsolePrintF(CC_DEFAULT, "Current debug-level: '%s'", GetDebugString());
1414 } else {
1415 SetDebugString(argv[1]);
1418 return true;
1421 DEF_CONSOLE_CMD(ConExit)
1423 if (argc == 0) {
1424 IConsoleHelp("Exit the game. Usage: 'exit'");
1425 return true;
1428 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
1430 _exit_game = true;
1431 return true;
1434 DEF_CONSOLE_CMD(ConPart)
1436 if (argc == 0) {
1437 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1438 return true;
1441 if (_game_mode != GM_NORMAL) return false;
1443 _switch_mode = SM_MENU;
1444 return true;
1447 DEF_CONSOLE_CMD(ConHelp)
1449 if (argc == 2) {
1450 const IConsoleCmd *cmd;
1451 const IConsoleAlias *alias;
1453 RemoveUnderscores(argv[1]);
1454 cmd = IConsoleCmdGet(argv[1]);
1455 if (cmd != NULL) {
1456 cmd->proc(0, NULL);
1457 return true;
1460 alias = IConsoleAliasGet(argv[1]);
1461 if (alias != NULL) {
1462 cmd = IConsoleCmdGet(alias->cmdline);
1463 if (cmd != NULL) {
1464 cmd->proc(0, NULL);
1465 return true;
1467 IConsolePrintF(CC_ERROR, "ERROR: alias is of special type, please see its execution-line: '%s'", alias->cmdline);
1468 return true;
1471 IConsoleError("command not found");
1472 return true;
1475 IConsolePrint(CC_WARNING, " ---- OpenTTD Console Help ---- ");
1476 IConsolePrint(CC_DEFAULT, " - commands: [command to list all commands: list_cmds]");
1477 IConsolePrint(CC_DEFAULT, " call commands with '<command> <arg2> <arg3>...'");
1478 IConsolePrint(CC_DEFAULT, " - to assign strings, or use them as arguments, enclose it within quotes");
1479 IConsolePrint(CC_DEFAULT, " like this: '<command> \"string argument with spaces\"'");
1480 IConsolePrint(CC_DEFAULT, " - use 'help <command>' to get specific information");
1481 IConsolePrint(CC_DEFAULT, " - scroll console output with shift + (up | down | pageup | pagedown)");
1482 IConsolePrint(CC_DEFAULT, " - scroll console input history with the up or down arrows");
1483 IConsolePrint(CC_DEFAULT, "");
1484 return true;
1487 DEF_CONSOLE_CMD(ConListCommands)
1489 if (argc == 0) {
1490 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1491 return true;
1494 for (const IConsoleCmd *cmd = _iconsole_cmds; cmd != NULL; cmd = cmd->next) {
1495 if (argv[1] == NULL || strstr(cmd->name, argv[1]) != NULL) {
1496 if (cmd->hook == NULL || cmd->hook(false) != CHR_HIDE) IConsolePrintF(CC_DEFAULT, "%s", cmd->name);
1500 return true;
1503 DEF_CONSOLE_CMD(ConListAliases)
1505 if (argc == 0) {
1506 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1507 return true;
1510 for (const IConsoleAlias *alias = _iconsole_aliases; alias != NULL; alias = alias->next) {
1511 if (argv[1] == NULL || strstr(alias->name, argv[1]) != NULL) {
1512 IConsolePrintF(CC_DEFAULT, "%s => %s", alias->name, alias->cmdline);
1516 return true;
1519 DEF_CONSOLE_CMD(ConCompanies)
1521 if (argc == 0) {
1522 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1523 return true;
1526 Company *c;
1527 FOR_ALL_COMPANIES(c) {
1528 /* Grab the company name */
1529 char company_name[512];
1530 SetDParam(0, c->index);
1531 GetString (company_name, STR_COMPANY_NAME);
1533 const char *password_state = "";
1534 if (c->is_ai) {
1535 password_state = "AI";
1537 #ifdef ENABLE_NETWORK
1538 else if (_network_server) {
1539 password_state = StrEmpty(_network_company_states[c->index].password) ? "unprotected" : "protected";
1541 #endif
1543 char colour[512];
1544 GetString (colour, STR_COLOUR_DARK_BLUE + _company_colours[c->index]);
1545 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",
1546 c->index + 1, colour, company_name,
1547 c->inaugurated_year, (int64)c->money, (int64)c->current_loan, (int64)CalculateCompanyValue(c),
1548 c->group_all[VEH_TRAIN].num_vehicle,
1549 c->group_all[VEH_ROAD].num_vehicle,
1550 c->group_all[VEH_AIRCRAFT].num_vehicle,
1551 c->group_all[VEH_SHIP].num_vehicle,
1552 password_state);
1555 return true;
1558 #ifdef ENABLE_NETWORK
1560 DEF_CONSOLE_CMD(ConSay)
1562 if (argc == 0) {
1563 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1564 return true;
1567 if (argc != 2) return false;
1569 if (!_network_server) {
1570 NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
1571 } else {
1572 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1573 NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin);
1576 return true;
1579 DEF_CONSOLE_CMD(ConSayCompany)
1581 if (argc == 0) {
1582 IConsoleHelp("Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'");
1583 IConsoleHelp("CompanyNo is the company that plays as company <companyno>, 1 through max_companies");
1584 return true;
1587 if (argc != 3) return false;
1589 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1590 if (!Company::IsValidID(company_id)) {
1591 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1592 return true;
1595 if (!_network_server) {
1596 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]);
1597 } else {
1598 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1599 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2], CLIENT_ID_SERVER, from_admin);
1602 return true;
1605 DEF_CONSOLE_CMD(ConSayClient)
1607 if (argc == 0) {
1608 IConsoleHelp("Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'");
1609 IConsoleHelp("For client-id's, see the command 'clients'");
1610 return true;
1613 if (argc != 3) return false;
1615 if (!_network_server) {
1616 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
1617 } else {
1618 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1619 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin);
1622 return true;
1625 DEF_CONSOLE_CMD(ConCompanyPassword)
1627 if (argc == 0) {
1628 const char *helpmsg;
1630 if (_network_dedicated) {
1631 helpmsg = "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\"";
1632 } else if (_network_server) {
1633 helpmsg = "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'";
1634 } else {
1635 helpmsg = "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1638 IConsoleHelp(helpmsg);
1639 IConsoleHelp("Use \"*\" to disable the password.");
1640 return true;
1643 CompanyID company_id;
1644 const char *password;
1645 const char *errormsg;
1647 if (argc == 2) {
1648 company_id = _local_company;
1649 password = argv[1];
1650 errormsg = "You have to own a company to make use of this command.";
1651 } else if (argc == 3 && _network_server) {
1652 company_id = (CompanyID)(atoi(argv[1]) - 1);
1653 password = argv[2];
1654 errormsg = "You have to specify the ID of a valid human controlled company.";
1655 } else {
1656 return false;
1659 if (!Company::IsValidHumanID(company_id)) {
1660 IConsoleError(errormsg);
1661 return false;
1664 password = NetworkChangeCompanyPassword(company_id, password);
1666 if (StrEmpty(password)) {
1667 IConsolePrintF(CC_WARNING, "Company password cleared");
1668 } else {
1669 IConsolePrintF(CC_WARNING, "Company password changed to: %s", password);
1672 return true;
1675 /* Content downloading only is available with ZLIB */
1676 #if defined(WITH_ZLIB)
1677 #include "network/network_content.h"
1679 /** Resolve a string to a content type. */
1680 static ContentType StringToContentType(const char *str)
1682 static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1683 for (uint i = 1 /* there is no type 0 */; i < lengthof(inv_lookup); i++) {
1684 if (strcasecmp(str, inv_lookup[i]) == 0) return (ContentType)i;
1686 return CONTENT_TYPE_END;
1689 /** Asynchronous callback */
1690 struct ConsoleContentCallback : public ContentCallback {
1691 void OnConnect(bool success)
1693 IConsolePrintF(CC_DEFAULT, "Content server connection %s", success ? "established" : "failed");
1696 void OnDisconnect()
1698 IConsolePrintF(CC_DEFAULT, "Content server connection closed");
1701 void OnDownloadComplete(ContentID cid)
1703 IConsolePrintF(CC_DEFAULT, "Completed download of %d", cid);
1708 * Outputs content state information to console
1709 * @param ci the content info
1711 static void OutputContentState(const ContentInfo *const ci)
1713 static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1714 assert_compile(lengthof(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN);
1715 static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1716 static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR };
1718 char buf[sizeof(ci->md5sum) * 2 + 1];
1719 md5sumToString (buf, ci->md5sum);
1720 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);
1723 DEF_CONSOLE_CMD(ConContent)
1725 static ContentCallback *cb = NULL;
1726 if (cb == NULL) {
1727 cb = new ConsoleContentCallback();
1728 _network_content_client.AddCallback(cb);
1731 if (argc <= 1) {
1732 IConsoleHelp("Query, select and download content. Usage: 'content update|upgrade|select [all|id]|unselect [all|id]|state [filter]|download'");
1733 IConsoleHelp(" update: get a new list of downloadable content; must be run first");
1734 IConsoleHelp(" upgrade: select all items that are upgrades");
1735 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");
1736 IConsoleHelp(" unselect: unselect a specific item given by its id or 'all' to unselect all");
1737 IConsoleHelp(" state: show the download/select state of all downloadable content. Optionally give a filter string");
1738 IConsoleHelp(" download: download all content you've selected");
1739 return true;
1742 if (strcasecmp(argv[1], "update") == 0) {
1743 _network_content_client.RequestContentList((argc > 2) ? StringToContentType(argv[2]) : CONTENT_TYPE_END);
1744 return true;
1747 if (strcasecmp(argv[1], "upgrade") == 0) {
1748 _network_content_client.SelectUpgrade();
1749 return true;
1752 if (strcasecmp(argv[1], "select") == 0) {
1753 if (argc <= 2) {
1754 /* List selected content */
1755 IConsolePrintF(CC_WHITE, "id, type, state, name");
1756 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1757 if ((*iter)->state != ContentInfo::SELECTED && (*iter)->state != ContentInfo::AUTOSELECTED) continue;
1758 OutputContentState(*iter);
1760 } else if (strcasecmp(argv[2], "all") == 0) {
1761 _network_content_client.SelectAll();
1762 } else {
1763 _network_content_client.Select((ContentID)atoi(argv[2]));
1765 return true;
1768 if (strcasecmp(argv[1], "unselect") == 0) {
1769 if (argc <= 2) {
1770 IConsoleError("You must enter the id.");
1771 return false;
1773 if (strcasecmp(argv[2], "all") == 0) {
1774 _network_content_client.UnselectAll();
1775 } else {
1776 _network_content_client.Unselect((ContentID)atoi(argv[2]));
1778 return true;
1781 if (strcasecmp(argv[1], "state") == 0) {
1782 IConsolePrintF(CC_WHITE, "id, type, state, name");
1783 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1784 if (argc > 2 && strcasestr((*iter)->name, argv[2]) == NULL) continue;
1785 OutputContentState(*iter);
1787 return true;
1790 if (strcasecmp(argv[1], "download") == 0) {
1791 uint files;
1792 uint bytes;
1793 _network_content_client.DownloadSelectedContent(files, bytes);
1794 IConsolePrintF(CC_DEFAULT, "Downloading %d file(s) (%d bytes)", files, bytes);
1795 return true;
1798 return false;
1800 #endif /* defined(WITH_ZLIB) */
1801 #endif /* ENABLE_NETWORK */
1803 DEF_CONSOLE_CMD(ConSetting)
1805 if (argc == 0) {
1806 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1807 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1808 return true;
1811 if (argc == 1 || argc > 3) return false;
1813 if (argc == 2) {
1814 IConsoleGetSetting(argv[1]);
1815 } else {
1816 IConsoleSetSetting(argv[1], argv[2]);
1819 return true;
1822 DEF_CONSOLE_CMD(ConSettingNewgame)
1824 if (argc == 0) {
1825 IConsoleHelp("Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'");
1826 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1827 return true;
1830 if (argc == 1 || argc > 3) return false;
1832 if (argc == 2) {
1833 IConsoleGetSetting(argv[1], true);
1834 } else {
1835 IConsoleSetSetting(argv[1], argv[2], true);
1838 return true;
1841 DEF_CONSOLE_CMD(ConListSettings)
1843 if (argc == 0) {
1844 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1845 return true;
1848 if (argc > 2) return false;
1850 IConsoleListSettings((argc == 2) ? argv[1] : NULL);
1851 return true;
1854 DEF_CONSOLE_CMD(ConGamelogPrint)
1856 GamelogPrintConsole();
1857 return true;
1860 DEF_CONSOLE_CMD(ConNewGRFReload)
1862 if (argc == 0) {
1863 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1864 return true;
1867 ReloadNewGRFData();
1868 return true;
1871 #ifdef _DEBUG
1872 /******************
1873 * debug commands
1874 ******************/
1876 static void IConsoleDebugLibRegister()
1878 IConsoleCmdRegister("resettile", ConResetTile);
1879 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
1880 IConsoleAliasRegister("dbg_echo2", "echo %!");
1882 #endif
1884 /*******************************
1885 * console command registration
1886 *******************************/
1888 void IConsoleStdLibRegister()
1890 IConsoleCmdRegister("debug_level", ConDebugLevel);
1891 IConsoleCmdRegister("echo", ConEcho);
1892 IConsoleCmdRegister("echoc", ConEchoC);
1893 IConsoleCmdRegister("exec", ConExec);
1894 IConsoleCmdRegister("exit", ConExit);
1895 IConsoleCmdRegister("part", ConPart);
1896 IConsoleCmdRegister("help", ConHelp);
1897 IConsoleCmdRegister("info_cmd", ConInfoCmd);
1898 IConsoleCmdRegister("list_cmds", ConListCommands);
1899 IConsoleCmdRegister("list_aliases", ConListAliases);
1900 IConsoleCmdRegister("newgame", ConNewGame);
1901 IConsoleCmdRegister("restart", ConRestart);
1902 IConsoleCmdRegister("getseed", ConGetSeed);
1903 IConsoleCmdRegister("getdate", ConGetDate);
1904 IConsoleCmdRegister("quit", ConExit);
1905 IConsoleCmdRegister("resetengines", ConResetEngines, ConHookNoNetwork);
1906 IConsoleCmdRegister("reset_enginepool", ConResetEnginePool, ConHookNoNetwork);
1907 IConsoleCmdRegister("return", ConReturn);
1908 IConsoleCmdRegister("screenshot", ConScreenShot);
1909 IConsoleCmdRegister("script", ConScript);
1910 IConsoleCmdRegister("scrollto", ConScrollToTile);
1911 IConsoleCmdRegister("alias", ConAlias);
1912 IConsoleCmdRegister("load", ConLoad);
1913 IConsoleCmdRegister("rm", ConRemove);
1914 IConsoleCmdRegister("save", ConSave);
1915 IConsoleCmdRegister("saveconfig", ConSaveConfig);
1916 IConsoleCmdRegister("ls", ConListFiles);
1917 IConsoleCmdRegister("cd", ConChangeDirectory);
1918 IConsoleCmdRegister("pwd", ConPrintWorkingDirectory);
1919 IConsoleCmdRegister("clear", ConClearBuffer);
1920 IConsoleCmdRegister("setting", ConSetting);
1921 IConsoleCmdRegister("setting_newgame", ConSettingNewgame);
1922 IConsoleCmdRegister("list_settings",ConListSettings);
1923 IConsoleCmdRegister("gamelog", ConGamelogPrint);
1924 IConsoleCmdRegister("rescan_newgrf", ConRescanNewGRF);
1926 IConsoleAliasRegister("dir", "ls");
1927 IConsoleAliasRegister("del", "rm %+");
1928 IConsoleAliasRegister("newmap", "newgame");
1929 IConsoleAliasRegister("patch", "setting %+");
1930 IConsoleAliasRegister("set", "setting %+");
1931 IConsoleAliasRegister("set_newgame", "setting_newgame %+");
1932 IConsoleAliasRegister("list_patches", "list_settings %+");
1933 IConsoleAliasRegister("developer", "setting developer %+");
1935 IConsoleCmdRegister("list_ai_libs", ConListAILibs);
1936 IConsoleCmdRegister("list_ai", ConListAI);
1937 IConsoleCmdRegister("reload_ai", ConReloadAI);
1938 IConsoleCmdRegister("rescan_ai", ConRescanAI);
1939 IConsoleCmdRegister("start_ai", ConStartAI);
1940 IConsoleCmdRegister("stop_ai", ConStopAI);
1942 IConsoleCmdRegister("list_game", ConListGame);
1943 IConsoleCmdRegister("list_game_libs", ConListGameLibs);
1944 IConsoleCmdRegister("rescan_game", ConRescanGame);
1946 IConsoleCmdRegister("companies", ConCompanies);
1947 IConsoleAliasRegister("players", "companies");
1949 /* networking functions */
1950 #ifdef ENABLE_NETWORK
1951 /* Content downloading is only available with ZLIB */
1952 #if defined(WITH_ZLIB)
1953 IConsoleCmdRegister("content", ConContent);
1954 #endif /* defined(WITH_ZLIB) */
1956 /*** Networking commands ***/
1957 IConsoleCmdRegister("say", ConSay, ConHookNeedNetwork);
1958 IConsoleCmdRegister("say_company", ConSayCompany, ConHookNeedNetwork);
1959 IConsoleAliasRegister("say_player", "say_company %+");
1960 IConsoleCmdRegister("say_client", ConSayClient, ConHookNeedNetwork);
1962 IConsoleCmdRegister("connect", ConNetworkConnect, ConHookClientOnly);
1963 IConsoleCmdRegister("clients", ConNetworkClients, ConHookNeedNetwork);
1964 IConsoleCmdRegister("status", ConStatus, ConHookServerOnly);
1965 IConsoleCmdRegister("server_info", ConServerInfo, ConHookServerOnly);
1966 IConsoleAliasRegister("info", "server_info");
1967 IConsoleCmdRegister("reconnect", ConNetworkReconnect, ConHookClientOnly);
1968 IConsoleCmdRegister("rcon", ConRcon, ConHookNeedNetwork);
1970 IConsoleCmdRegister("join", ConJoinCompany, ConHookNeedNetwork);
1971 IConsoleAliasRegister("spectate", "join 255");
1972 IConsoleCmdRegister("move", ConMoveClient, ConHookServerOnly);
1973 IConsoleCmdRegister("reset_company", ConResetCompany, ConHookServerOnly);
1974 IConsoleAliasRegister("clean_company", "reset_company %A");
1975 IConsoleCmdRegister("client_name", ConClientNickChange, ConHookServerOnly);
1976 IConsoleCmdRegister("kick", ConKick, ConHookServerOnly);
1977 IConsoleCmdRegister("ban", ConBan, ConHookServerOnly);
1978 IConsoleCmdRegister("unban", ConUnBan, ConHookServerOnly);
1979 IConsoleCmdRegister("banlist", ConBanList, ConHookServerOnly);
1981 IConsoleCmdRegister("pause", ConPauseGame, ConHookServerOnly);
1982 IConsoleCmdRegister("unpause", ConUnpauseGame, ConHookServerOnly);
1984 IConsoleCmdRegister("company_pw", ConCompanyPassword, ConHookNeedNetwork);
1985 IConsoleAliasRegister("company_password", "company_pw %+");
1987 IConsoleAliasRegister("net_frame_freq", "setting frame_freq %+");
1988 IConsoleAliasRegister("net_sync_freq", "setting sync_freq %+");
1989 IConsoleAliasRegister("server_pw", "setting server_password %+");
1990 IConsoleAliasRegister("server_password", "setting server_password %+");
1991 IConsoleAliasRegister("rcon_pw", "setting rcon_password %+");
1992 IConsoleAliasRegister("rcon_password", "setting rcon_password %+");
1993 IConsoleAliasRegister("name", "setting client_name %+");
1994 IConsoleAliasRegister("server_name", "setting server_name %+");
1995 IConsoleAliasRegister("server_port", "setting server_port %+");
1996 IConsoleAliasRegister("server_advertise", "setting server_advertise %+");
1997 IConsoleAliasRegister("max_clients", "setting max_clients %+");
1998 IConsoleAliasRegister("max_companies", "setting max_companies %+");
1999 IConsoleAliasRegister("max_spectators", "setting max_spectators %+");
2000 IConsoleAliasRegister("max_join_time", "setting max_join_time %+");
2001 IConsoleAliasRegister("pause_on_join", "setting pause_on_join %+");
2002 IConsoleAliasRegister("autoclean_companies", "setting autoclean_companies %+");
2003 IConsoleAliasRegister("autoclean_protected", "setting autoclean_protected %+");
2004 IConsoleAliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2005 IConsoleAliasRegister("restart_game_year", "setting restart_game_year %+");
2006 IConsoleAliasRegister("min_players", "setting min_active_clients %+");
2007 IConsoleAliasRegister("reload_cfg", "setting reload_cfg %+");
2008 #endif /* ENABLE_NETWORK */
2010 /* debugging stuff */
2011 #ifdef _DEBUG
2012 IConsoleDebugLibRegister();
2013 #endif
2015 /* NewGRF development stuff */
2016 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload, ConHookNewGRFDeveloperTool);