Doc: Clarify comment that SND_05_TRAIN_THROUGH_TUNNEL is only for steam engines ...
[openttd-github.git] / src / console_cmds.cpp
blobf50644cf5bef77dd7729afda89e93239aec83026
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file console_cmds.cpp Implementation of the console hooks. */
10 #include "stdafx.h"
11 #include "console_internal.h"
12 #include "debug.h"
13 #include "engine_func.h"
14 #include "landscape.h"
15 #include "saveload/saveload.h"
16 #include "network/network.h"
17 #include "network/network_func.h"
18 #include "network/network_base.h"
19 #include "network/network_admin.h"
20 #include "network/network_client.h"
21 #include "command_func.h"
22 #include "settings_func.h"
23 #include "fios.h"
24 #include "fileio_func.h"
25 #include "screenshot.h"
26 #include "genworld.h"
27 #include "strings_func.h"
28 #include "viewport_func.h"
29 #include "window_func.h"
30 #include "date_func.h"
31 #include "company_func.h"
32 #include "gamelog.h"
33 #include "ai/ai.hpp"
34 #include "ai/ai_config.hpp"
35 #include "newgrf.h"
36 #include "newgrf_profiling.h"
37 #include "console_func.h"
38 #include "engine_base.h"
39 #include "road.h"
40 #include "rail.h"
41 #include "game/game.hpp"
42 #include "table/strings.h"
43 #include <time.h>
45 #include "safeguards.h"
47 /* scriptfile handling */
48 static uint _script_current_depth; ///< Depth of scripts running (used to abort execution when #ConReturn is encountered).
50 /** File list storage for the console, for caching the last 'ls' command. */
51 class ConsoleFileList : public FileList {
52 public:
53 ConsoleFileList() : FileList()
55 this->file_list_valid = false;
58 /** Declare the file storage cache as being invalid, also clears all stored files. */
59 void InvalidateFileList()
61 this->Clear();
62 this->file_list_valid = false;
65 /**
66 * (Re-)validate the file storage cache. Only makes a change if the storage was invalid, or if \a force_reload.
67 * @param force_reload Always reload the file storage cache.
69 void ValidateFileList(bool force_reload = false)
71 if (force_reload || !this->file_list_valid) {
72 this->BuildFileList(FT_SAVEGAME, SLO_LOAD);
73 this->file_list_valid = true;
77 bool file_list_valid; ///< If set, the file list is valid.
80 static ConsoleFileList _console_file_list; ///< File storage cache for the console.
82 /* console command defines */
83 #define DEF_CONSOLE_CMD(function) static bool function(byte argc, char *argv[])
84 #define DEF_CONSOLE_HOOK(function) static ConsoleHookResult function(bool echo)
87 /****************
88 * command hooks
89 ****************/
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 singleplayer 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 DEF_CONSOLE_HOOK(ConHookNewGRFDeveloperTool)
164 if (_settings_client.gui.newgrf_developer_tools) {
165 if (_game_mode == GM_MENU) {
166 if (echo) IConsoleError("This command is only available in game and editor.");
167 return CHR_DISALLOW;
169 return ConHookNoNetwork(echo);
171 return CHR_HIDE;
175 * Show help for the console.
176 * @param str String to print in the console.
178 static void IConsoleHelp(const char *str)
180 IConsolePrintF(CC_WARNING, "- %s", str);
184 * Reset status of all engines.
185 * @return Will always succeed.
187 DEF_CONSOLE_CMD(ConResetEngines)
189 if (argc == 0) {
190 IConsoleHelp("Reset status data of all engines. This might solve some issues with 'lost' engines. Usage: 'resetengines'");
191 return true;
194 StartupEngines();
195 return true;
199 * Reset status of the engine pool.
200 * @return Will always return true.
201 * @note Resetting the pool only succeeds when there are no vehicles ingame.
203 DEF_CONSOLE_CMD(ConResetEnginePool)
205 if (argc == 0) {
206 IConsoleHelp("Reset NewGRF allocations of engine slots. This will remove invalid engine definitions, and might make default engines available again.");
207 return true;
210 if (_game_mode == GM_MENU) {
211 IConsoleError("This command is only available in game and editor.");
212 return true;
215 if (!EngineOverrideManager::ResetToCurrentNewGRFConfig()) {
216 IConsoleError("This can only be done when there are no vehicles in the game.");
217 return true;
220 return true;
223 #ifdef _DEBUG
225 * Reset a tile to bare land in debug mode.
226 * param tile number.
227 * @return True when the tile is reset or the help on usage was printed (0 or two parameters).
229 DEF_CONSOLE_CMD(ConResetTile)
231 if (argc == 0) {
232 IConsoleHelp("Reset a tile to bare land. Usage: 'resettile <tile>'");
233 IConsoleHelp("Tile can be either decimal (34161) or hexadecimal (0x4a5B)");
234 return true;
237 if (argc == 2) {
238 uint32 result;
239 if (GetArgumentInteger(&result, argv[1])) {
240 DoClearSquare((TileIndex)result);
241 return true;
245 return false;
247 #endif /* _DEBUG */
250 * Scroll to a tile on the map.
251 * param x tile number or tile x coordinate.
252 * param y optional y coordinate.
253 * @note When only one argument is given it is interpreted as the tile number.
254 * When two arguments are given, they are interpreted as the tile's x
255 * and y coordinates.
256 * @return True when either console help was shown or a proper amount of parameters given.
258 DEF_CONSOLE_CMD(ConScrollToTile)
260 switch (argc) {
261 case 0:
262 IConsoleHelp("Center the screen on a given tile.");
263 IConsoleHelp("Usage: 'scrollto <tile>' or 'scrollto <x> <y>'");
264 IConsoleHelp("Numbers can be either decimal (34161) or hexadecimal (0x4a5B).");
265 return true;
267 case 2: {
268 uint32 result;
269 if (GetArgumentInteger(&result, argv[1])) {
270 if (result >= MapSize()) {
271 IConsolePrint(CC_ERROR, "Tile does not exist");
272 return true;
274 ScrollMainWindowToTile((TileIndex)result);
275 return true;
277 break;
280 case 3: {
281 uint32 x, y;
282 if (GetArgumentInteger(&x, argv[1]) && GetArgumentInteger(&y, argv[2])) {
283 if (x >= MapSizeX() || y >= MapSizeY()) {
284 IConsolePrint(CC_ERROR, "Tile does not exist");
285 return true;
287 ScrollMainWindowToTile(TileXY(x, y));
288 return true;
290 break;
294 return false;
298 * Save the map to a file.
299 * param filename the filename to save the map to.
300 * @return True when help was displayed or the file attempted to be saved.
302 DEF_CONSOLE_CMD(ConSave)
304 if (argc == 0) {
305 IConsoleHelp("Save the current game. Usage: 'save <filename>'");
306 return true;
309 if (argc == 2) {
310 char *filename = str_fmt("%s.sav", argv[1]);
311 IConsolePrint(CC_DEFAULT, "Saving map...");
313 if (SaveOrLoad(filename, SLO_SAVE, DFT_GAME_FILE, SAVE_DIR) != SL_OK) {
314 IConsolePrint(CC_ERROR, "Saving map failed");
315 } else {
316 IConsolePrintF(CC_DEFAULT, "Map successfully saved to %s", filename);
318 free(filename);
319 return true;
322 return false;
326 * Explicitly save the configuration.
327 * @return True.
329 DEF_CONSOLE_CMD(ConSaveConfig)
331 if (argc == 0) {
332 IConsoleHelp("Saves the configuration for new games to the configuration file, typically 'openttd.cfg'.");
333 IConsoleHelp("It does not save the configuration of the current game to the configuration file.");
334 return true;
337 SaveToConfig();
338 IConsolePrint(CC_DEFAULT, "Saved config.");
339 return true;
342 DEF_CONSOLE_CMD(ConLoad)
344 if (argc == 0) {
345 IConsoleHelp("Load a game by name or index. Usage: 'load <file | number>'");
346 return true;
349 if (argc != 2) return false;
351 const char *file = argv[1];
352 _console_file_list.ValidateFileList();
353 const FiosItem *item = _console_file_list.FindItem(file);
354 if (item != nullptr) {
355 if (GetAbstractFileType(item->type) == FT_SAVEGAME) {
356 _switch_mode = SM_LOAD_GAME;
357 _file_to_saveload.SetMode(item->type);
358 _file_to_saveload.SetName(FiosBrowseTo(item));
359 _file_to_saveload.SetTitle(item->title);
360 } else {
361 IConsolePrintF(CC_ERROR, "%s: Not a savegame.", file);
363 } else {
364 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
367 return true;
371 DEF_CONSOLE_CMD(ConRemove)
373 if (argc == 0) {
374 IConsoleHelp("Remove a savegame by name or index. Usage: 'rm <file | number>'");
375 return true;
378 if (argc != 2) return false;
380 const char *file = argv[1];
381 _console_file_list.ValidateFileList();
382 const FiosItem *item = _console_file_list.FindItem(file);
383 if (item != nullptr) {
384 if (!FiosDelete(item->name)) {
385 IConsolePrintF(CC_ERROR, "%s: Failed to delete file", file);
387 } else {
388 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
391 _console_file_list.InvalidateFileList();
392 return true;
396 /* List all the files in the current dir via console */
397 DEF_CONSOLE_CMD(ConListFiles)
399 if (argc == 0) {
400 IConsoleHelp("List all loadable savegames and directories in the current dir via console. Usage: 'ls | dir'");
401 return true;
404 _console_file_list.ValidateFileList(true);
405 for (uint i = 0; i < _console_file_list.Length(); i++) {
406 IConsolePrintF(CC_DEFAULT, "%d) %s", i, _console_file_list[i].title);
409 return true;
412 /* Change the dir via console */
413 DEF_CONSOLE_CMD(ConChangeDirectory)
415 if (argc == 0) {
416 IConsoleHelp("Change the dir via console. Usage: 'cd <directory | number>'");
417 return true;
420 if (argc != 2) return false;
422 const char *file = argv[1];
423 _console_file_list.ValidateFileList(true);
424 const FiosItem *item = _console_file_list.FindItem(file);
425 if (item != nullptr) {
426 switch (item->type) {
427 case FIOS_TYPE_DIR: case FIOS_TYPE_DRIVE: case FIOS_TYPE_PARENT:
428 FiosBrowseTo(item);
429 break;
430 default: IConsolePrintF(CC_ERROR, "%s: Not a directory.", file);
432 } else {
433 IConsolePrintF(CC_ERROR, "%s: No such file or directory.", file);
436 _console_file_list.InvalidateFileList();
437 return true;
440 DEF_CONSOLE_CMD(ConPrintWorkingDirectory)
442 const char *path;
444 if (argc == 0) {
445 IConsoleHelp("Print out the current working directory. Usage: 'pwd'");
446 return true;
449 /* XXX - Workaround for broken file handling */
450 _console_file_list.ValidateFileList(true);
451 _console_file_list.InvalidateFileList();
453 FiosGetDescText(&path, nullptr);
454 IConsolePrint(CC_DEFAULT, path);
455 return true;
458 DEF_CONSOLE_CMD(ConClearBuffer)
460 if (argc == 0) {
461 IConsoleHelp("Clear the console buffer. Usage: 'clear'");
462 return true;
465 IConsoleClearBuffer();
466 SetWindowDirty(WC_CONSOLE, 0);
467 return true;
471 /**********************************
472 * Network Core Console Commands
473 **********************************/
475 static bool ConKickOrBan(const char *argv, bool ban, const char *reason)
477 uint n;
479 if (strchr(argv, '.') == nullptr && strchr(argv, ':') == nullptr) { // banning with ID
480 ClientID client_id = (ClientID)atoi(argv);
482 /* Don't kill the server, or the client doing the rcon. The latter can't be kicked because
483 * kicking frees closes and subsequently free the connection related instances, which we
484 * would be reading from and writing to after returning. So we would read or write data
485 * from freed memory up till the segfault triggers. */
486 if (client_id == CLIENT_ID_SERVER || client_id == _redirect_console_to_client) {
487 IConsolePrintF(CC_ERROR, "ERROR: Silly boy, you can not %s yourself!", ban ? "ban" : "kick");
488 return true;
491 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id);
492 if (ci == nullptr) {
493 IConsoleError("Invalid client");
494 return true;
497 if (!ban) {
498 /* Kick only this client, not all clients with that IP */
499 NetworkServerKickClient(client_id, reason);
500 return true;
503 /* When banning, kick+ban all clients with that IP */
504 n = NetworkServerKickOrBanIP(client_id, ban, reason);
505 } else {
506 n = NetworkServerKickOrBanIP(argv, ban, reason);
509 if (n == 0) {
510 IConsolePrint(CC_DEFAULT, ban ? "Client not online, address added to banlist" : "Client not found");
511 } else {
512 IConsolePrintF(CC_DEFAULT, "%sed %u client(s)", ban ? "Bann" : "Kick", n);
515 return true;
518 DEF_CONSOLE_CMD(ConKick)
520 if (argc == 0) {
521 IConsoleHelp("Kick a client from a network game. Usage: 'kick <ip | client-id> [<kick-reason>]'");
522 IConsoleHelp("For client-id's, see the command 'clients'");
523 return true;
526 if (argc != 2 && argc != 3) return false;
528 /* No reason supplied for kicking */
529 if (argc == 2) return ConKickOrBan(argv[1], false, nullptr);
531 /* Reason for kicking supplied */
532 size_t kick_message_length = strlen(argv[2]);
533 if (kick_message_length >= 255) {
534 IConsolePrintF(CC_ERROR, "ERROR: Maximum kick message length is 254 characters. You entered " PRINTF_SIZE " characters.", kick_message_length);
535 return false;
536 } else {
537 return ConKickOrBan(argv[1], false, argv[2]);
541 DEF_CONSOLE_CMD(ConBan)
543 if (argc == 0) {
544 IConsoleHelp("Ban a client from a network game. Usage: 'ban <ip | client-id> [<ban-reason>]'");
545 IConsoleHelp("For client-id's, see the command 'clients'");
546 IConsoleHelp("If the client is no longer online, you can still ban his/her IP");
547 return true;
550 if (argc != 2 && argc != 3) return false;
552 /* No reason supplied for kicking */
553 if (argc == 2) return ConKickOrBan(argv[1], true, nullptr);
555 /* Reason for kicking supplied */
556 size_t kick_message_length = strlen(argv[2]);
557 if (kick_message_length >= 255) {
558 IConsolePrintF(CC_ERROR, "ERROR: Maximum kick message length is 254 characters. You entered " PRINTF_SIZE " characters.", kick_message_length);
559 return false;
560 } else {
561 return ConKickOrBan(argv[1], true, argv[2]);
565 DEF_CONSOLE_CMD(ConUnBan)
567 if (argc == 0) {
568 IConsoleHelp("Unban a client from a network game. Usage: 'unban <ip | banlist-index>'");
569 IConsoleHelp("For a list of banned IP's, see the command 'banlist'");
570 return true;
573 if (argc != 2) return false;
575 /* Try by IP. */
576 uint index;
577 for (index = 0; index < _network_ban_list.size(); index++) {
578 if (_network_ban_list[index] == argv[1]) break;
581 /* Try by index. */
582 if (index >= _network_ban_list.size()) {
583 index = atoi(argv[1]) - 1U; // let it wrap
586 if (index < _network_ban_list.size()) {
587 char msg[64];
588 seprintf(msg, lastof(msg), "Unbanned %s", _network_ban_list[index].c_str());
589 IConsolePrint(CC_DEFAULT, msg);
590 _network_ban_list.erase(_network_ban_list.begin() + index);
591 } else {
592 IConsolePrint(CC_DEFAULT, "Invalid list index or IP not in ban-list.");
593 IConsolePrint(CC_DEFAULT, "For a list of banned IP's, see the command 'banlist'");
596 return true;
599 DEF_CONSOLE_CMD(ConBanList)
601 if (argc == 0) {
602 IConsoleHelp("List the IP's of banned clients: Usage 'banlist'");
603 return true;
606 IConsolePrint(CC_DEFAULT, "Banlist: ");
608 uint i = 1;
609 for (const auto &entry : _network_ban_list) {
610 IConsolePrintF(CC_DEFAULT, " %d) %s", i, entry.c_str());
611 i++;
614 return true;
617 DEF_CONSOLE_CMD(ConPauseGame)
619 if (argc == 0) {
620 IConsoleHelp("Pause a network game. Usage: 'pause'");
621 return true;
624 if ((_pause_mode & PM_PAUSED_NORMAL) == PM_UNPAUSED) {
625 DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
626 if (!_networking) IConsolePrint(CC_DEFAULT, "Game paused.");
627 } else {
628 IConsolePrint(CC_DEFAULT, "Game is already paused.");
631 return true;
634 DEF_CONSOLE_CMD(ConUnpauseGame)
636 if (argc == 0) {
637 IConsoleHelp("Unpause a network game. Usage: 'unpause'");
638 return true;
641 if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) {
642 DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE);
643 if (!_networking) IConsolePrint(CC_DEFAULT, "Game unpaused.");
644 } else if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED) {
645 IConsolePrint(CC_DEFAULT, "Game is in error state and cannot be unpaused via console.");
646 } else if (_pause_mode != PM_UNPAUSED) {
647 IConsolePrint(CC_DEFAULT, "Game cannot be unpaused manually; disable pause_on_join/min_active_clients.");
648 } else {
649 IConsolePrint(CC_DEFAULT, "Game is already unpaused.");
652 return true;
655 DEF_CONSOLE_CMD(ConRcon)
657 if (argc == 0) {
658 IConsoleHelp("Remote control the server from another client. Usage: 'rcon <password> <command>'");
659 IConsoleHelp("Remember to enclose the command in quotes, otherwise only the first parameter is sent");
660 return true;
663 if (argc < 3) return false;
665 if (_network_server) {
666 IConsoleCmdExec(argv[2]);
667 } else {
668 NetworkClientSendRcon(argv[1], argv[2]);
670 return true;
673 DEF_CONSOLE_CMD(ConStatus)
675 if (argc == 0) {
676 IConsoleHelp("List the status of all clients connected to the server. Usage 'status'");
677 return true;
680 NetworkServerShowStatusToConsole();
681 return true;
684 DEF_CONSOLE_CMD(ConServerInfo)
686 if (argc == 0) {
687 IConsoleHelp("List current and maximum client/company limits. Usage 'server_info'");
688 IConsoleHelp("You can change these values by modifying settings 'network.max_clients', 'network.max_companies' and 'network.max_spectators'");
689 return true;
692 IConsolePrintF(CC_DEFAULT, "Current/maximum clients: %2d/%2d", _network_game_info.clients_on, _settings_client.network.max_clients);
693 IConsolePrintF(CC_DEFAULT, "Current/maximum companies: %2d/%2d", (int)Company::GetNumItems(), _settings_client.network.max_companies);
694 IConsolePrintF(CC_DEFAULT, "Current/maximum spectators: %2d/%2d", NetworkSpectatorCount(), _settings_client.network.max_spectators);
696 return true;
699 DEF_CONSOLE_CMD(ConClientNickChange)
701 if (argc != 3) {
702 IConsoleHelp("Change the nickname of a connected client. Usage: 'client_name <client-id> <new-name>'");
703 IConsoleHelp("For client-id's, see the command 'clients'");
704 return true;
707 ClientID client_id = (ClientID)atoi(argv[1]);
709 if (client_id == CLIENT_ID_SERVER) {
710 IConsoleError("Please use the command 'name' to change your own name!");
711 return true;
714 if (NetworkClientInfo::GetByClientID(client_id) == nullptr) {
715 IConsoleError("Invalid client");
716 return true;
719 if (!NetworkServerChangeClientName(client_id, argv[2])) {
720 IConsoleError("Cannot give a client a duplicate name");
723 return true;
726 DEF_CONSOLE_CMD(ConJoinCompany)
728 if (argc < 2) {
729 IConsoleHelp("Request joining another company. Usage: join <company-id> [<password>]");
730 IConsoleHelp("For valid company-id see company list, use 255 for spectator");
731 return true;
734 CompanyID company_id = (CompanyID)(atoi(argv[1]) <= MAX_COMPANIES ? atoi(argv[1]) - 1 : atoi(argv[1]));
736 /* Check we have a valid company id! */
737 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
738 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
739 return true;
742 if (NetworkClientInfo::GetByClientID(_network_own_client_id)->client_playas == company_id) {
743 IConsoleError("You are already there!");
744 return true;
747 if (company_id == COMPANY_SPECTATOR && NetworkMaxSpectatorsReached()) {
748 IConsoleError("Cannot join spectators, maximum number of spectators reached.");
749 return true;
752 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
753 IConsoleError("Cannot join AI company.");
754 return true;
757 /* Check if the company requires a password */
758 if (NetworkCompanyIsPassworded(company_id) && argc < 3) {
759 IConsolePrintF(CC_ERROR, "Company %d requires a password to join.", company_id + 1);
760 return true;
763 /* non-dedicated server may just do the move! */
764 if (_network_server) {
765 NetworkServerDoMove(CLIENT_ID_SERVER, company_id);
766 } else {
767 NetworkClientRequestMove(company_id, NetworkCompanyIsPassworded(company_id) ? argv[2] : "");
770 return true;
773 DEF_CONSOLE_CMD(ConMoveClient)
775 if (argc < 3) {
776 IConsoleHelp("Move a client to another company. Usage: move <client-id> <company-id>");
777 IConsoleHelp("For valid client-id see 'clients', for valid company-id see 'companies', use 255 for moving to spectators");
778 return true;
781 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID((ClientID)atoi(argv[1]));
782 CompanyID company_id = (CompanyID)(atoi(argv[2]) <= MAX_COMPANIES ? atoi(argv[2]) - 1 : atoi(argv[2]));
784 /* check the client exists */
785 if (ci == nullptr) {
786 IConsoleError("Invalid client-id, check the command 'clients' for valid client-id's.");
787 return true;
790 if (!Company::IsValidID(company_id) && company_id != COMPANY_SPECTATOR) {
791 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
792 return true;
795 if (company_id != COMPANY_SPECTATOR && !Company::IsHumanID(company_id)) {
796 IConsoleError("You cannot move clients to AI companies.");
797 return true;
800 if (ci->client_id == CLIENT_ID_SERVER && _network_dedicated) {
801 IConsoleError("Silly boy, you cannot move the server!");
802 return true;
805 if (ci->client_playas == company_id) {
806 IConsoleError("You cannot move someone to where he/she already is!");
807 return true;
810 /* we are the server, so force the update */
811 NetworkServerDoMove(ci->client_id, company_id);
813 return true;
816 DEF_CONSOLE_CMD(ConResetCompany)
818 if (argc == 0) {
819 IConsoleHelp("Remove an idle company from the game. Usage: 'reset_company <company-id>'");
820 IConsoleHelp("For company-id's, see the list of companies from the dropdown menu. Company 1 is 1, etc.");
821 return true;
824 if (argc != 2) return false;
826 CompanyID index = (CompanyID)(atoi(argv[1]) - 1);
828 /* Check valid range */
829 if (!Company::IsValidID(index)) {
830 IConsolePrintF(CC_ERROR, "Company does not exist. Company-id must be between 1 and %d.", MAX_COMPANIES);
831 return true;
834 if (!Company::IsHumanID(index)) {
835 IConsoleError("Company is owned by an AI.");
836 return true;
839 if (NetworkCompanyHasClients(index)) {
840 IConsoleError("Cannot remove company: a client is connected to that company.");
841 return false;
843 const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER);
844 if (ci->client_playas == index) {
845 IConsoleError("Cannot remove company: the server is connected to that company.");
846 return true;
849 /* It is safe to remove this company */
850 DoCommandP(0, CCA_DELETE | index << 16 | CRR_MANUAL << 24, 0, CMD_COMPANY_CTRL);
851 IConsolePrint(CC_DEFAULT, "Company deleted.");
853 return true;
856 DEF_CONSOLE_CMD(ConNetworkClients)
858 if (argc == 0) {
859 IConsoleHelp("Get a list of connected clients including their ID, name, company-id, and IP. Usage: 'clients'");
860 return true;
863 NetworkPrintClients();
865 return true;
868 DEF_CONSOLE_CMD(ConNetworkReconnect)
870 if (argc == 0) {
871 IConsoleHelp("Reconnect to server to which you were connected last time. Usage: 'reconnect [<company>]'");
872 IConsoleHelp("Company 255 is spectator (default, if not specified), 0 means creating new company.");
873 IConsoleHelp("All others are a certain company with Company 1 being #1");
874 return true;
877 CompanyID playas = (argc >= 2) ? (CompanyID)atoi(argv[1]) : COMPANY_SPECTATOR;
878 switch (playas) {
879 case 0: playas = COMPANY_NEW_COMPANY; break;
880 case COMPANY_SPECTATOR: /* nothing to do */ break;
881 default:
882 /* From a user pov 0 is a new company, internally it's different and all
883 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
884 if (playas < COMPANY_FIRST + 1 || playas > MAX_COMPANIES + 1) return false;
885 break;
888 if (StrEmpty(_settings_client.network.last_host)) {
889 IConsolePrint(CC_DEFAULT, "No server for reconnecting.");
890 return true;
893 /* Don't resolve the address first, just print it directly as it comes from the config file. */
894 IConsolePrintF(CC_DEFAULT, "Reconnecting to %s:%d...", _settings_client.network.last_host, _settings_client.network.last_port);
896 NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port), playas);
897 return true;
900 DEF_CONSOLE_CMD(ConNetworkConnect)
902 if (argc == 0) {
903 IConsoleHelp("Connect to a remote OTTD server and join the game. Usage: 'connect <ip>'");
904 IConsoleHelp("IP can contain port and company: 'IP[:Port][#Company]', eg: 'server.ottd.org:443#2'");
905 IConsoleHelp("Company #255 is spectator all others are a certain company with Company 1 being #1");
906 return true;
909 if (argc < 2) return false;
910 if (_networking) NetworkDisconnect(); // we are in network-mode, first close it!
912 const char *port = nullptr;
913 const char *company = nullptr;
914 char *ip = argv[1];
915 /* Default settings: default port and new company */
916 uint16 rport = NETWORK_DEFAULT_PORT;
917 CompanyID join_as = COMPANY_NEW_COMPANY;
919 ParseConnectionString(&company, &port, ip);
921 IConsolePrintF(CC_DEFAULT, "Connecting to %s...", ip);
922 if (company != nullptr) {
923 join_as = (CompanyID)atoi(company);
924 IConsolePrintF(CC_DEFAULT, " company-no: %d", join_as);
926 /* From a user pov 0 is a new company, internally it's different and all
927 * companies are offset by one to ease up on users (eg companies 1-8 not 0-7) */
928 if (join_as != COMPANY_SPECTATOR) {
929 if (join_as > MAX_COMPANIES) return false;
930 join_as--;
933 if (port != nullptr) {
934 rport = atoi(port);
935 IConsolePrintF(CC_DEFAULT, " port: %s", port);
938 NetworkClientConnectGame(NetworkAddress(ip, rport), join_as);
940 return true;
943 /*********************************
944 * script file console commands
945 *********************************/
947 DEF_CONSOLE_CMD(ConExec)
949 if (argc == 0) {
950 IConsoleHelp("Execute a local script file. Usage: 'exec <script> <?>'");
951 return true;
954 if (argc < 2) return false;
956 FILE *script_file = FioFOpenFile(argv[1], "r", BASE_DIR);
958 if (script_file == nullptr) {
959 if (argc == 2 || atoi(argv[2]) != 0) IConsoleError("script file not found");
960 return true;
963 if (_script_current_depth == 11) {
964 IConsoleError("Maximum 'exec' depth reached; script A is calling script B is calling script C ... more than 10 times.");
965 return true;
968 _script_current_depth++;
969 uint script_depth = _script_current_depth;
971 char cmdline[ICON_CMDLN_SIZE];
972 while (fgets(cmdline, sizeof(cmdline), script_file) != nullptr) {
973 /* Remove newline characters from the executing script */
974 for (char *cmdptr = cmdline; *cmdptr != '\0'; cmdptr++) {
975 if (*cmdptr == '\n' || *cmdptr == '\r') {
976 *cmdptr = '\0';
977 break;
980 IConsoleCmdExec(cmdline);
981 /* Ensure that we are still on the same depth or that we returned via 'return'. */
982 assert(_script_current_depth == script_depth || _script_current_depth == script_depth - 1);
984 /* The 'return' command was executed. */
985 if (_script_current_depth == script_depth - 1) break;
988 if (ferror(script_file)) {
989 IConsoleError("Encountered error while trying to read from script file");
992 if (_script_current_depth == script_depth) _script_current_depth--;
993 FioFCloseFile(script_file);
994 return true;
997 DEF_CONSOLE_CMD(ConReturn)
999 if (argc == 0) {
1000 IConsoleHelp("Stop executing a running script. Usage: 'return'");
1001 return true;
1004 _script_current_depth--;
1005 return true;
1008 /*****************************
1009 * default console commands
1010 ******************************/
1011 extern bool CloseConsoleLogIfActive();
1013 DEF_CONSOLE_CMD(ConScript)
1015 extern FILE *_iconsole_output_file;
1017 if (argc == 0) {
1018 IConsoleHelp("Start or stop logging console output to a file. Usage: 'script <filename>'");
1019 IConsoleHelp("If filename is omitted, a running log is stopped if it is active");
1020 return true;
1023 if (!CloseConsoleLogIfActive()) {
1024 if (argc < 2) return false;
1026 IConsolePrintF(CC_DEFAULT, "file output started to: %s", argv[1]);
1027 _iconsole_output_file = fopen(argv[1], "ab");
1028 if (_iconsole_output_file == nullptr) IConsoleError("could not open file");
1031 return true;
1035 DEF_CONSOLE_CMD(ConEcho)
1037 if (argc == 0) {
1038 IConsoleHelp("Print back the first argument to the console. Usage: 'echo <arg>'");
1039 return true;
1042 if (argc < 2) return false;
1043 IConsolePrint(CC_DEFAULT, argv[1]);
1044 return true;
1047 DEF_CONSOLE_CMD(ConEchoC)
1049 if (argc == 0) {
1050 IConsoleHelp("Print back the first argument to the console in a given colour. Usage: 'echoc <colour> <arg2>'");
1051 return true;
1054 if (argc < 3) return false;
1055 IConsolePrint((TextColour)Clamp(atoi(argv[1]), TC_BEGIN, TC_END - 1), argv[2]);
1056 return true;
1059 DEF_CONSOLE_CMD(ConNewGame)
1061 if (argc == 0) {
1062 IConsoleHelp("Start a new game. Usage: 'newgame [seed]'");
1063 IConsoleHelp("The server can force a new game using 'newgame'; any client joined will rejoin after the server is done generating the new game.");
1064 return true;
1067 StartNewGameWithoutGUI((argc == 2) ? strtoul(argv[1], nullptr, 10) : GENERATE_NEW_SEED);
1068 return true;
1071 DEF_CONSOLE_CMD(ConRestart)
1073 if (argc == 0) {
1074 IConsoleHelp("Restart game. Usage: 'restart'");
1075 IConsoleHelp("Restarts a game. It tries to reproduce the exact same map as the game started with.");
1076 IConsoleHelp("However:");
1077 IConsoleHelp(" * restarting games started in another version might create another map due to difference in map generation");
1078 IConsoleHelp(" * restarting games based on scenarios, loaded games or heightmaps will start a new game based on the settings stored in the scenario/savegame");
1079 return true;
1082 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1083 _settings_game.game_creation.map_x = MapLogX();
1084 _settings_game.game_creation.map_y = FindFirstBit(MapSizeY());
1085 _switch_mode = SM_RESTARTGAME;
1086 return true;
1089 DEF_CONSOLE_CMD(ConReload)
1091 if (argc == 0) {
1092 IConsoleHelp("Reload game. Usage: 'reload'");
1093 IConsoleHelp("Reloads a game.");
1094 IConsoleHelp(" * if you started from a savegame / scenario / heightmap, that exact same savegame / scenario / heightmap will be loaded.");
1095 IConsoleHelp(" * if you started from a new game, this acts the same as 'restart'.");
1096 return true;
1099 /* Don't copy the _newgame pointers to the real pointers, so call SwitchToMode directly */
1100 _settings_game.game_creation.map_x = MapLogX();
1101 _settings_game.game_creation.map_y = FindFirstBit(MapSizeY());
1102 _switch_mode = SM_RELOADGAME;
1103 return true;
1107 * Print a text buffer line by line to the console. Lines are separated by '\n'.
1108 * @param buf The buffer to print.
1109 * @note All newlines are replace by '\0' characters.
1111 static void PrintLineByLine(char *buf)
1113 char *p = buf;
1114 /* Print output line by line */
1115 for (char *p2 = buf; *p2 != '\0'; p2++) {
1116 if (*p2 == '\n') {
1117 *p2 = '\0';
1118 IConsolePrintF(CC_DEFAULT, "%s", p);
1119 p = p2 + 1;
1124 DEF_CONSOLE_CMD(ConListAILibs)
1126 char buf[4096];
1127 AI::GetConsoleLibraryList(buf, lastof(buf));
1129 PrintLineByLine(buf);
1131 return true;
1134 DEF_CONSOLE_CMD(ConListAI)
1136 char buf[4096];
1137 AI::GetConsoleList(buf, lastof(buf));
1139 PrintLineByLine(buf);
1141 return true;
1144 DEF_CONSOLE_CMD(ConListGameLibs)
1146 char buf[4096];
1147 Game::GetConsoleLibraryList(buf, lastof(buf));
1149 PrintLineByLine(buf);
1151 return true;
1154 DEF_CONSOLE_CMD(ConListGame)
1156 char buf[4096];
1157 Game::GetConsoleList(buf, lastof(buf));
1159 PrintLineByLine(buf);
1161 return true;
1164 DEF_CONSOLE_CMD(ConStartAI)
1166 if (argc == 0 || argc > 3) {
1167 IConsoleHelp("Start a new AI. Usage: 'start_ai [<AI>] [<settings>]'");
1168 IConsoleHelp("Start a new AI. If <AI> is given, it starts that specific AI (if found).");
1169 IConsoleHelp("If <settings> is given, it is parsed and the AI settings are set to that.");
1170 return true;
1173 if (_game_mode != GM_NORMAL) {
1174 IConsoleWarning("AIs can only be managed in a game.");
1175 return true;
1178 if (Company::GetNumItems() == CompanyPool::MAX_SIZE) {
1179 IConsoleWarning("Can't start a new AI (no more free slots).");
1180 return true;
1182 if (_networking && !_network_server) {
1183 IConsoleWarning("Only the server can start a new AI.");
1184 return true;
1186 if (_networking && !_settings_game.ai.ai_in_multiplayer) {
1187 IConsoleWarning("AIs are not allowed in multiplayer by configuration.");
1188 IConsoleWarning("Switch AI -> AI in multiplayer to True.");
1189 return true;
1191 if (!AI::CanStartNew()) {
1192 IConsoleWarning("Can't start a new AI.");
1193 return true;
1196 int n = 0;
1197 /* Find the next free slot */
1198 for (const Company *c : Company::Iterate()) {
1199 if (c->index != n) break;
1200 n++;
1203 AIConfig *config = AIConfig::GetConfig((CompanyID)n);
1204 if (argc >= 2) {
1205 config->Change(argv[1], -1, false);
1207 /* If the name is not found, and there is a dot in the name,
1208 * try again with the assumption everything right of the dot is
1209 * the version the user wants to load. */
1210 if (!config->HasScript()) {
1211 char *name = stredup(argv[1]);
1212 char *e = strrchr(name, '.');
1213 if (e != nullptr) {
1214 *e = '\0';
1215 e++;
1217 int version = atoi(e);
1218 config->Change(name, version, true);
1220 free(name);
1223 if (!config->HasScript()) {
1224 IConsoleWarning("Failed to load the specified AI");
1225 return true;
1227 if (argc == 3) {
1228 config->StringToSettings(argv[2]);
1232 /* Start a new AI company */
1233 DoCommandP(0, CCA_NEW_AI | INVALID_COMPANY << 16, 0, CMD_COMPANY_CTRL);
1235 return true;
1238 DEF_CONSOLE_CMD(ConReloadAI)
1240 if (argc != 2) {
1241 IConsoleHelp("Reload an AI. Usage: 'reload_ai <company-id>'");
1242 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.");
1243 return true;
1246 if (_game_mode != GM_NORMAL) {
1247 IConsoleWarning("AIs can only be managed in a game.");
1248 return true;
1251 if (_networking && !_network_server) {
1252 IConsoleWarning("Only the server can reload an AI.");
1253 return true;
1256 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1257 if (!Company::IsValidID(company_id)) {
1258 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1259 return true;
1262 /* In singleplayer mode the player can be in an AI company, after cheating or loading network save with an AI in first slot. */
1263 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1264 IConsoleWarning("Company is not controlled by an AI.");
1265 return true;
1268 /* First kill the company of the AI, then start a new one. This should start the current AI again */
1269 DoCommandP(0, CCA_DELETE | company_id << 16 | CRR_MANUAL << 24, 0, CMD_COMPANY_CTRL);
1270 DoCommandP(0, CCA_NEW_AI | company_id << 16, 0, CMD_COMPANY_CTRL);
1271 IConsolePrint(CC_DEFAULT, "AI reloaded.");
1273 return true;
1276 DEF_CONSOLE_CMD(ConStopAI)
1278 if (argc != 2) {
1279 IConsoleHelp("Stop an AI. Usage: 'stop_ai <company-id>'");
1280 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.");
1281 return true;
1284 if (_game_mode != GM_NORMAL) {
1285 IConsoleWarning("AIs can only be managed in a game.");
1286 return true;
1289 if (_networking && !_network_server) {
1290 IConsoleWarning("Only the server can stop an AI.");
1291 return true;
1294 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1295 if (!Company::IsValidID(company_id)) {
1296 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1297 return true;
1300 /* In singleplayer mode the player can be in an AI company, after cheating or loading network save with an AI in first slot. */
1301 if (Company::IsHumanID(company_id) || company_id == _local_company) {
1302 IConsoleWarning("Company is not controlled by an AI.");
1303 return true;
1306 /* Now kill the company of the AI. */
1307 DoCommandP(0, CCA_DELETE | company_id << 16 | CRR_MANUAL << 24, 0, CMD_COMPANY_CTRL);
1308 IConsolePrint(CC_DEFAULT, "AI stopped, company deleted.");
1310 return true;
1313 DEF_CONSOLE_CMD(ConRescanAI)
1315 if (argc == 0) {
1316 IConsoleHelp("Rescan the AI dir for scripts. Usage: 'rescan_ai'");
1317 return true;
1320 if (_networking && !_network_server) {
1321 IConsoleWarning("Only the server can rescan the AI dir for scripts.");
1322 return true;
1325 AI::Rescan();
1327 return true;
1330 DEF_CONSOLE_CMD(ConRescanGame)
1332 if (argc == 0) {
1333 IConsoleHelp("Rescan the Game Script dir for scripts. Usage: 'rescan_game'");
1334 return true;
1337 if (_networking && !_network_server) {
1338 IConsoleWarning("Only the server can rescan the Game Script dir for scripts.");
1339 return true;
1342 Game::Rescan();
1344 return true;
1347 DEF_CONSOLE_CMD(ConRescanNewGRF)
1349 if (argc == 0) {
1350 IConsoleHelp("Rescan the data dir for NewGRFs. Usage: 'rescan_newgrf'");
1351 return true;
1354 RequestNewGRFScan();
1356 return true;
1359 DEF_CONSOLE_CMD(ConGetSeed)
1361 if (argc == 0) {
1362 IConsoleHelp("Returns the seed used to create this game. Usage: 'getseed'");
1363 IConsoleHelp("The seed can be used to reproduce the exact same map as the game started with.");
1364 return true;
1367 IConsolePrintF(CC_DEFAULT, "Generation Seed: %u", _settings_game.game_creation.generation_seed);
1368 return true;
1371 DEF_CONSOLE_CMD(ConGetDate)
1373 if (argc == 0) {
1374 IConsoleHelp("Returns the current date (year-month-day) of the game. Usage: 'getdate'");
1375 return true;
1378 YearMonthDay ymd;
1379 ConvertDateToYMD(_date, &ymd);
1380 IConsolePrintF(CC_DEFAULT, "Date: %04d-%02d-%02d", ymd.year, ymd.month + 1, ymd.day);
1381 return true;
1384 DEF_CONSOLE_CMD(ConGetSysDate)
1386 if (argc == 0) {
1387 IConsoleHelp("Returns the current date (year-month-day) of your system. Usage: 'getsysdate'");
1388 return true;
1391 time_t t;
1392 time(&t);
1393 auto timeinfo = localtime(&t);
1394 IConsolePrintF(CC_DEFAULT, "System Date: %04d-%02d-%02d %02d:%02d:%02d", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
1395 return true;
1399 DEF_CONSOLE_CMD(ConAlias)
1401 IConsoleAlias *alias;
1403 if (argc == 0) {
1404 IConsoleHelp("Add a new alias, or redefine the behaviour of an existing alias . Usage: 'alias <name> <command>'");
1405 return true;
1408 if (argc < 3) return false;
1410 alias = IConsoleAliasGet(argv[1]);
1411 if (alias == nullptr) {
1412 IConsoleAliasRegister(argv[1], argv[2]);
1413 } else {
1414 free(alias->cmdline);
1415 alias->cmdline = stredup(argv[2]);
1417 return true;
1420 DEF_CONSOLE_CMD(ConScreenShot)
1422 if (argc == 0) {
1423 IConsoleHelp("Create a screenshot of the game. Usage: 'screenshot [viewport | normal | big | giant | heightmap | minimap] [no_con] [size <width> <height>] [<filename>]'");
1424 IConsoleHelp("'viewport' (default) makes a screenshot of the current viewport (including menus, windows, ..), "
1425 "'normal' makes a screenshot of the visible area, "
1426 "'big' makes a zoomed-in screenshot of the visible area, "
1427 "'giant' makes a screenshot of the whole map, "
1428 "'heightmap' makes a heightmap screenshot of the map that can be loaded in as heightmap, "
1429 "'minimap' makes a top-viewed minimap screenshot of the whole world which represents one tile by one pixel. "
1430 "'no_con' hides the console to create the screenshot (only useful in combination with 'viewport'). "
1431 "'size' sets the width and height of the viewport to make a screenshot of (only useful in combination with 'normal' or 'big').");
1432 return true;
1435 if (argc > 7) return false;
1437 ScreenshotType type = SC_VIEWPORT;
1438 uint32 width = 0;
1439 uint32 height = 0;
1440 const char *name = nullptr;
1441 uint32 arg_index = 1;
1443 if (argc > arg_index) {
1444 if (strcmp(argv[arg_index], "viewport") == 0) {
1445 type = SC_VIEWPORT;
1446 arg_index += 1;
1447 } else if (strcmp(argv[arg_index], "normal") == 0) {
1448 type = SC_DEFAULTZOOM;
1449 arg_index += 1;
1450 } else if (strcmp(argv[arg_index], "big") == 0) {
1451 type = SC_ZOOMEDIN;
1452 arg_index += 1;
1453 } else if (strcmp(argv[arg_index], "giant") == 0) {
1454 type = SC_WORLD;
1455 arg_index += 1;
1456 } else if (strcmp(argv[arg_index], "heightmap") == 0) {
1457 type = SC_HEIGHTMAP;
1458 arg_index += 1;
1459 } else if (strcmp(argv[arg_index], "minimap") == 0) {
1460 type = SC_MINIMAP;
1461 arg_index += 1;
1465 if (argc > arg_index && strcmp(argv[arg_index], "no_con") == 0) {
1466 if (type != SC_VIEWPORT) {
1467 IConsoleError("'no_con' can only be used in combination with 'viewport'");
1468 return true;
1470 IConsoleClose();
1471 arg_index += 1;
1474 if (argc > arg_index + 2 && strcmp(argv[arg_index], "size") == 0) {
1475 /* size <width> <height> */
1476 if (type != SC_DEFAULTZOOM && type != SC_ZOOMEDIN) {
1477 IConsoleError("'size' can only be used in combination with 'normal' or 'big'");
1478 return true;
1480 GetArgumentInteger(&width, argv[arg_index + 1]);
1481 GetArgumentInteger(&height, argv[arg_index + 2]);
1482 arg_index += 3;
1485 if (argc > arg_index) {
1486 /* Last parameter that was not one of the keywords must be the filename. */
1487 name = argv[arg_index];
1488 arg_index += 1;
1491 if (argc > arg_index) {
1492 /* We have parameters we did not process; means we misunderstood any of the above. */
1493 return false;
1496 MakeScreenshot(type, name, width, height);
1497 return true;
1500 DEF_CONSOLE_CMD(ConInfoCmd)
1502 if (argc == 0) {
1503 IConsoleHelp("Print out debugging information about a command. Usage: 'info_cmd <cmd>'");
1504 return true;
1507 if (argc < 2) return false;
1509 const IConsoleCmd *cmd = IConsoleCmdGet(argv[1]);
1510 if (cmd == nullptr) {
1511 IConsoleError("the given command was not found");
1512 return true;
1515 IConsolePrintF(CC_DEFAULT, "command name: %s", cmd->name);
1516 IConsolePrintF(CC_DEFAULT, "command proc: %p", cmd->proc);
1518 if (cmd->hook != nullptr) IConsoleWarning("command is hooked");
1520 return true;
1523 DEF_CONSOLE_CMD(ConDebugLevel)
1525 if (argc == 0) {
1526 IConsoleHelp("Get/set the default debugging level for the game. Usage: 'debug_level [<level>]'");
1527 IConsoleHelp("Level can be any combination of names, levels. Eg 'net=5 ms=4'. Remember to enclose it in \"'s");
1528 return true;
1531 if (argc > 2) return false;
1533 if (argc == 1) {
1534 IConsolePrintF(CC_DEFAULT, "Current debug-level: '%s'", GetDebugString());
1535 } else {
1536 SetDebugString(argv[1]);
1539 return true;
1542 DEF_CONSOLE_CMD(ConExit)
1544 if (argc == 0) {
1545 IConsoleHelp("Exit the game. Usage: 'exit'");
1546 return true;
1549 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
1551 _exit_game = true;
1552 return true;
1555 DEF_CONSOLE_CMD(ConPart)
1557 if (argc == 0) {
1558 IConsoleHelp("Leave the currently joined/running game (only ingame). Usage: 'part'");
1559 return true;
1562 if (_game_mode != GM_NORMAL) return false;
1564 _switch_mode = SM_MENU;
1565 return true;
1568 DEF_CONSOLE_CMD(ConHelp)
1570 if (argc == 2) {
1571 const IConsoleCmd *cmd;
1572 const IConsoleAlias *alias;
1574 RemoveUnderscores(argv[1]);
1575 cmd = IConsoleCmdGet(argv[1]);
1576 if (cmd != nullptr) {
1577 cmd->proc(0, nullptr);
1578 return true;
1581 alias = IConsoleAliasGet(argv[1]);
1582 if (alias != nullptr) {
1583 cmd = IConsoleCmdGet(alias->cmdline);
1584 if (cmd != nullptr) {
1585 cmd->proc(0, nullptr);
1586 return true;
1588 IConsolePrintF(CC_ERROR, "ERROR: alias is of special type, please see its execution-line: '%s'", alias->cmdline);
1589 return true;
1592 IConsoleError("command not found");
1593 return true;
1596 IConsolePrint(CC_WARNING, " ---- OpenTTD Console Help ---- ");
1597 IConsolePrint(CC_DEFAULT, " - commands: [command to list all commands: list_cmds]");
1598 IConsolePrint(CC_DEFAULT, " call commands with '<command> <arg2> <arg3>...'");
1599 IConsolePrint(CC_DEFAULT, " - to assign strings, or use them as arguments, enclose it within quotes");
1600 IConsolePrint(CC_DEFAULT, " like this: '<command> \"string argument with spaces\"'");
1601 IConsolePrint(CC_DEFAULT, " - use 'help <command>' to get specific information");
1602 IConsolePrint(CC_DEFAULT, " - scroll console output with shift + (up | down | pageup | pagedown)");
1603 IConsolePrint(CC_DEFAULT, " - scroll console input history with the up or down arrows");
1604 IConsolePrint(CC_DEFAULT, "");
1605 return true;
1608 DEF_CONSOLE_CMD(ConListCommands)
1610 if (argc == 0) {
1611 IConsoleHelp("List all registered commands. Usage: 'list_cmds [<pre-filter>]'");
1612 return true;
1615 for (const IConsoleCmd *cmd = _iconsole_cmds; cmd != nullptr; cmd = cmd->next) {
1616 if (argv[1] == nullptr || strstr(cmd->name, argv[1]) != nullptr) {
1617 if (cmd->hook == nullptr || cmd->hook(false) != CHR_HIDE) IConsolePrintF(CC_DEFAULT, "%s", cmd->name);
1621 return true;
1624 DEF_CONSOLE_CMD(ConListAliases)
1626 if (argc == 0) {
1627 IConsoleHelp("List all registered aliases. Usage: 'list_aliases [<pre-filter>]'");
1628 return true;
1631 for (const IConsoleAlias *alias = _iconsole_aliases; alias != nullptr; alias = alias->next) {
1632 if (argv[1] == nullptr || strstr(alias->name, argv[1]) != nullptr) {
1633 IConsolePrintF(CC_DEFAULT, "%s => %s", alias->name, alias->cmdline);
1637 return true;
1640 DEF_CONSOLE_CMD(ConCompanies)
1642 if (argc == 0) {
1643 IConsoleHelp("List the details of all companies in the game. Usage 'companies'");
1644 return true;
1647 for (const Company *c : Company::Iterate()) {
1648 /* Grab the company name */
1649 char company_name[512];
1650 SetDParam(0, c->index);
1651 GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
1653 const char *password_state = "";
1654 if (c->is_ai) {
1655 password_state = "AI";
1656 } else if (_network_server) {
1657 password_state = StrEmpty(_network_company_states[c->index].password) ? "unprotected" : "protected";
1660 char colour[512];
1661 GetString(colour, STR_COLOUR_DARK_BLUE + _company_colours[c->index], lastof(colour));
1662 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",
1663 c->index + 1, colour, company_name,
1664 c->inaugurated_year, (int64)c->money, (int64)c->current_loan, (int64)CalculateCompanyValue(c),
1665 c->group_all[VEH_TRAIN].num_vehicle,
1666 c->group_all[VEH_ROAD].num_vehicle,
1667 c->group_all[VEH_AIRCRAFT].num_vehicle,
1668 c->group_all[VEH_SHIP].num_vehicle,
1669 password_state);
1672 return true;
1675 DEF_CONSOLE_CMD(ConSay)
1677 if (argc == 0) {
1678 IConsoleHelp("Chat to your fellow players in a multiplayer game. Usage: 'say \"<msg>\"'");
1679 return true;
1682 if (argc != 2) return false;
1684 if (!_network_server) {
1685 NetworkClientSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0 /* param does not matter */, argv[1]);
1686 } else {
1687 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1688 NetworkServerSendChat(NETWORK_ACTION_CHAT, DESTTYPE_BROADCAST, 0, argv[1], CLIENT_ID_SERVER, from_admin);
1691 return true;
1694 DEF_CONSOLE_CMD(ConSayCompany)
1696 if (argc == 0) {
1697 IConsoleHelp("Chat to a certain company in a multiplayer game. Usage: 'say_company <company-no> \"<msg>\"'");
1698 IConsoleHelp("CompanyNo is the company that plays as company <companyno>, 1 through max_companies");
1699 return true;
1702 if (argc != 3) return false;
1704 CompanyID company_id = (CompanyID)(atoi(argv[1]) - 1);
1705 if (!Company::IsValidID(company_id)) {
1706 IConsolePrintF(CC_DEFAULT, "Unknown company. Company range is between 1 and %d.", MAX_COMPANIES);
1707 return true;
1710 if (!_network_server) {
1711 NetworkClientSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2]);
1712 } else {
1713 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1714 NetworkServerSendChat(NETWORK_ACTION_CHAT_COMPANY, DESTTYPE_TEAM, company_id, argv[2], CLIENT_ID_SERVER, from_admin);
1717 return true;
1720 DEF_CONSOLE_CMD(ConSayClient)
1722 if (argc == 0) {
1723 IConsoleHelp("Chat to a certain client in a multiplayer game. Usage: 'say_client <client-no> \"<msg>\"'");
1724 IConsoleHelp("For client-id's, see the command 'clients'");
1725 return true;
1728 if (argc != 3) return false;
1730 if (!_network_server) {
1731 NetworkClientSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2]);
1732 } else {
1733 bool from_admin = (_redirect_console_to_admin < INVALID_ADMIN_ID);
1734 NetworkServerSendChat(NETWORK_ACTION_CHAT_CLIENT, DESTTYPE_CLIENT, atoi(argv[1]), argv[2], CLIENT_ID_SERVER, from_admin);
1737 return true;
1740 DEF_CONSOLE_CMD(ConCompanyPassword)
1742 if (argc == 0) {
1743 const char *helpmsg;
1745 if (_network_dedicated) {
1746 helpmsg = "Change the password of a company. Usage: 'company_pw <company-no> \"<password>\"";
1747 } else if (_network_server) {
1748 helpmsg = "Change the password of your or any other company. Usage: 'company_pw [<company-no>] \"<password>\"'";
1749 } else {
1750 helpmsg = "Change the password of your company. Usage: 'company_pw \"<password>\"'";
1753 IConsoleHelp(helpmsg);
1754 IConsoleHelp("Use \"*\" to disable the password.");
1755 return true;
1758 CompanyID company_id;
1759 const char *password;
1760 const char *errormsg;
1762 if (argc == 2) {
1763 company_id = _local_company;
1764 password = argv[1];
1765 errormsg = "You have to own a company to make use of this command.";
1766 } else if (argc == 3 && _network_server) {
1767 company_id = (CompanyID)(atoi(argv[1]) - 1);
1768 password = argv[2];
1769 errormsg = "You have to specify the ID of a valid human controlled company.";
1770 } else {
1771 return false;
1774 if (!Company::IsValidHumanID(company_id)) {
1775 IConsoleError(errormsg);
1776 return false;
1779 password = NetworkChangeCompanyPassword(company_id, password);
1781 if (StrEmpty(password)) {
1782 IConsolePrintF(CC_WARNING, "Company password cleared");
1783 } else {
1784 IConsolePrintF(CC_WARNING, "Company password changed to: %s", password);
1787 return true;
1790 /* Content downloading only is available with ZLIB */
1791 #if defined(WITH_ZLIB)
1792 #include "network/network_content.h"
1794 /** Resolve a string to a content type. */
1795 static ContentType StringToContentType(const char *str)
1797 static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
1798 for (uint i = 1 /* there is no type 0 */; i < lengthof(inv_lookup); i++) {
1799 if (strcasecmp(str, inv_lookup[i]) == 0) return (ContentType)i;
1801 return CONTENT_TYPE_END;
1804 /** Asynchronous callback */
1805 struct ConsoleContentCallback : public ContentCallback {
1806 void OnConnect(bool success)
1808 IConsolePrintF(CC_DEFAULT, "Content server connection %s", success ? "established" : "failed");
1811 void OnDisconnect()
1813 IConsolePrintF(CC_DEFAULT, "Content server connection closed");
1816 void OnDownloadComplete(ContentID cid)
1818 IConsolePrintF(CC_DEFAULT, "Completed download of %d", cid);
1823 * Outputs content state information to console
1824 * @param ci the content info
1826 static void OutputContentState(const ContentInfo *const ci)
1828 static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
1829 static_assert(lengthof(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN);
1830 static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
1831 static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR };
1833 char buf[sizeof(ci->md5sum) * 2 + 1];
1834 md5sumToString(buf, lastof(buf), ci->md5sum);
1835 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);
1838 DEF_CONSOLE_CMD(ConContent)
1840 static ContentCallback *cb = nullptr;
1841 if (cb == nullptr) {
1842 cb = new ConsoleContentCallback();
1843 _network_content_client.AddCallback(cb);
1846 if (argc <= 1) {
1847 IConsoleHelp("Query, select and download content. Usage: 'content update|upgrade|select [id]|unselect [all|id]|state [filter]|download'");
1848 IConsoleHelp(" update: get a new list of downloadable content; must be run first");
1849 IConsoleHelp(" upgrade: select all items that are upgrades");
1850 IConsoleHelp(" select: select a specific item given by its id. If no parameter is given, all selected content will be listed");
1851 IConsoleHelp(" unselect: unselect a specific item given by its id or 'all' to unselect all");
1852 IConsoleHelp(" state: show the download/select state of all downloadable content. Optionally give a filter string");
1853 IConsoleHelp(" download: download all content you've selected");
1854 return true;
1857 if (strcasecmp(argv[1], "update") == 0) {
1858 _network_content_client.RequestContentList((argc > 2) ? StringToContentType(argv[2]) : CONTENT_TYPE_END);
1859 return true;
1862 if (strcasecmp(argv[1], "upgrade") == 0) {
1863 _network_content_client.SelectUpgrade();
1864 return true;
1867 if (strcasecmp(argv[1], "select") == 0) {
1868 if (argc <= 2) {
1869 /* List selected content */
1870 IConsolePrintF(CC_WHITE, "id, type, state, name");
1871 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1872 if ((*iter)->state != ContentInfo::SELECTED && (*iter)->state != ContentInfo::AUTOSELECTED) continue;
1873 OutputContentState(*iter);
1875 } else if (strcasecmp(argv[2], "all") == 0) {
1876 /* The intention of this function was that you could download
1877 * everything after a filter was applied; but this never really
1878 * took off. Instead, a select few people used this functionality
1879 * to download every available package on BaNaNaS. This is not in
1880 * the spirit of this service. Additionally, these few people were
1881 * good for 70% of the consumed bandwidth of BaNaNaS. */
1882 IConsoleError("'select all' is no longer supported since 1.11");
1883 } else {
1884 _network_content_client.Select((ContentID)atoi(argv[2]));
1886 return true;
1889 if (strcasecmp(argv[1], "unselect") == 0) {
1890 if (argc <= 2) {
1891 IConsoleError("You must enter the id.");
1892 return false;
1894 if (strcasecmp(argv[2], "all") == 0) {
1895 _network_content_client.UnselectAll();
1896 } else {
1897 _network_content_client.Unselect((ContentID)atoi(argv[2]));
1899 return true;
1902 if (strcasecmp(argv[1], "state") == 0) {
1903 IConsolePrintF(CC_WHITE, "id, type, state, name");
1904 for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
1905 if (argc > 2 && strcasestr((*iter)->name, argv[2]) == nullptr) continue;
1906 OutputContentState(*iter);
1908 return true;
1911 if (strcasecmp(argv[1], "download") == 0) {
1912 uint files;
1913 uint bytes;
1914 _network_content_client.DownloadSelectedContent(files, bytes);
1915 IConsolePrintF(CC_DEFAULT, "Downloading %d file(s) (%d bytes)", files, bytes);
1916 return true;
1919 return false;
1921 #endif /* defined(WITH_ZLIB) */
1923 DEF_CONSOLE_CMD(ConSetting)
1925 if (argc == 0) {
1926 IConsoleHelp("Change setting for all clients. Usage: 'setting <name> [<value>]'");
1927 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1928 return true;
1931 if (argc == 1 || argc > 3) return false;
1933 if (argc == 2) {
1934 IConsoleGetSetting(argv[1]);
1935 } else {
1936 IConsoleSetSetting(argv[1], argv[2]);
1939 return true;
1942 DEF_CONSOLE_CMD(ConSettingNewgame)
1944 if (argc == 0) {
1945 IConsoleHelp("Change setting for the next game. Usage: 'setting_newgame <name> [<value>]'");
1946 IConsoleHelp("Omitting <value> will print out the current value of the setting.");
1947 return true;
1950 if (argc == 1 || argc > 3) return false;
1952 if (argc == 2) {
1953 IConsoleGetSetting(argv[1], true);
1954 } else {
1955 IConsoleSetSetting(argv[1], argv[2], true);
1958 return true;
1961 DEF_CONSOLE_CMD(ConListSettings)
1963 if (argc == 0) {
1964 IConsoleHelp("List settings. Usage: 'list_settings [<pre-filter>]'");
1965 return true;
1968 if (argc > 2) return false;
1970 IConsoleListSettings((argc == 2) ? argv[1] : nullptr);
1971 return true;
1974 DEF_CONSOLE_CMD(ConGamelogPrint)
1976 GamelogPrintConsole();
1977 return true;
1980 DEF_CONSOLE_CMD(ConNewGRFReload)
1982 if (argc == 0) {
1983 IConsoleHelp("Reloads all active NewGRFs from disk. Equivalent to reapplying NewGRFs via the settings, but without asking for confirmation. This might crash OpenTTD!");
1984 return true;
1987 ReloadNewGRFData();
1988 return true;
1991 DEF_CONSOLE_CMD(ConNewGRFProfile)
1993 if (argc == 0) {
1994 IConsoleHelp("Collect performance data about NewGRF sprite requests and callbacks. Sub-commands can be abbreviated.");
1995 IConsoleHelp("Usage: newgrf_profile [list]");
1996 IConsoleHelp(" List all NewGRFs that can be profiled, and their status.");
1997 IConsoleHelp("Usage: newgrf_profile select <grf-num>...");
1998 IConsoleHelp(" Select one or more GRFs for profiling.");
1999 IConsoleHelp("Usage: newgrf_profile unselect <grf-num>...");
2000 IConsoleHelp(" Unselect one or more GRFs from profiling. Use the keyword \"all\" instead of a GRF number to unselect all. Removing an active profiler aborts data collection.");
2001 IConsoleHelp("Usage: newgrf_profile start [<num-days>]");
2002 IConsoleHelp(" Begin profiling all selected GRFs. If a number of days is provided, profiling stops after that many in-game days.");
2003 IConsoleHelp("Usage: newgrf_profile stop");
2004 IConsoleHelp(" End profiling and write the collected data to CSV files.");
2005 IConsoleHelp("Usage: newgrf_profile abort");
2006 IConsoleHelp(" End profiling and discard all collected data.");
2007 return true;
2010 extern const std::vector<GRFFile *> &GetAllGRFFiles();
2011 const std::vector<GRFFile *> &files = GetAllGRFFiles();
2013 /* "list" sub-command */
2014 if (argc == 1 || strncasecmp(argv[1], "lis", 3) == 0) {
2015 IConsolePrint(CC_INFO, "Loaded GRF files:");
2016 int i = 1;
2017 for (GRFFile *grf : files) {
2018 auto profiler = std::find_if(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; });
2019 bool selected = profiler != _newgrf_profilers.end();
2020 bool active = selected && profiler->active;
2021 TextColour tc = active ? TC_LIGHT_BLUE : selected ? TC_GREEN : CC_INFO;
2022 const char *statustext = active ? " (active)" : selected ? " (selected)" : "";
2023 IConsolePrintF(tc, "%d: [%08X] %s%s", i, BSWAP32(grf->grfid), grf->filename, statustext);
2024 i++;
2026 return true;
2029 /* "select" sub-command */
2030 if (strncasecmp(argv[1], "sel", 3) == 0 && argc >= 3) {
2031 for (size_t argnum = 2; argnum < argc; ++argnum) {
2032 int grfnum = atoi(argv[argnum]);
2033 if (grfnum < 1 || grfnum > (int)files.size()) { // safe cast, files.size() should not be larger than a few hundred in the most extreme cases
2034 IConsolePrintF(CC_WARNING, "GRF number %d out of range, not added.", grfnum);
2035 continue;
2037 GRFFile *grf = files[grfnum - 1];
2038 if (std::any_of(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; })) {
2039 IConsolePrintF(CC_WARNING, "GRF number %d [%08X] is already selected for profiling.", grfnum, BSWAP32(grf->grfid));
2040 continue;
2042 _newgrf_profilers.emplace_back(grf);
2044 return true;
2047 /* "unselect" sub-command */
2048 if (strncasecmp(argv[1], "uns", 3) == 0 && argc >= 3) {
2049 for (size_t argnum = 2; argnum < argc; ++argnum) {
2050 if (strcasecmp(argv[argnum], "all") == 0) {
2051 _newgrf_profilers.clear();
2052 break;
2054 int grfnum = atoi(argv[argnum]);
2055 if (grfnum < 1 || grfnum > (int)files.size()) {
2056 IConsolePrintF(CC_WARNING, "GRF number %d out of range, not removing.", grfnum);
2057 continue;
2059 GRFFile *grf = files[grfnum - 1];
2060 auto pos = std::find_if(_newgrf_profilers.begin(), _newgrf_profilers.end(), [&](NewGRFProfiler &pr) { return pr.grffile == grf; });
2061 if (pos != _newgrf_profilers.end()) _newgrf_profilers.erase(pos);
2063 return true;
2066 /* "start" sub-command */
2067 if (strncasecmp(argv[1], "sta", 3) == 0) {
2068 std::string grfids;
2069 size_t started = 0;
2070 for (NewGRFProfiler &pr : _newgrf_profilers) {
2071 if (!pr.active) {
2072 pr.Start();
2073 started++;
2075 if (!grfids.empty()) grfids += ", ";
2076 char grfidstr[12]{ 0 };
2077 seprintf(grfidstr, lastof(grfidstr), "[%08X]", BSWAP32(pr.grffile->grfid));
2078 grfids += grfidstr;
2081 if (started > 0) {
2082 IConsolePrintF(CC_DEBUG, "Started profiling for GRFID%s %s", (started > 1) ? "s" : "", grfids.c_str());
2083 if (argc >= 3) {
2084 int days = std::max(atoi(argv[2]), 1);
2085 _newgrf_profile_end_date = _date + days;
2087 char datestrbuf[32]{ 0 };
2088 SetDParam(0, _newgrf_profile_end_date);
2089 GetString(datestrbuf, STR_JUST_DATE_ISO, lastof(datestrbuf));
2090 IConsolePrintF(CC_DEBUG, "Profiling will automatically stop on game date %s", datestrbuf);
2091 } else {
2092 _newgrf_profile_end_date = MAX_DAY;
2094 } else if (_newgrf_profilers.empty()) {
2095 IConsolePrintF(CC_WARNING, "No GRFs selected for profiling, did not start.");
2096 } else {
2097 IConsolePrintF(CC_WARNING, "Did not start profiling for any GRFs, all selected GRFs are already profiling.");
2099 return true;
2102 /* "stop" sub-command */
2103 if (strncasecmp(argv[1], "sto", 3) == 0) {
2104 NewGRFProfiler::FinishAll();
2105 return true;
2108 /* "abort" sub-command */
2109 if (strncasecmp(argv[1], "abo", 3) == 0) {
2110 for (NewGRFProfiler &pr : _newgrf_profilers) {
2111 pr.Abort();
2113 _newgrf_profile_end_date = MAX_DAY;
2114 return true;
2117 return false;
2120 #ifdef _DEBUG
2121 /******************
2122 * debug commands
2123 ******************/
2125 static void IConsoleDebugLibRegister()
2127 IConsoleCmdRegister("resettile", ConResetTile);
2128 IConsoleAliasRegister("dbg_echo", "echo %A; echo %B");
2129 IConsoleAliasRegister("dbg_echo2", "echo %!");
2131 #endif
2133 DEF_CONSOLE_CMD(ConFramerate)
2135 extern void ConPrintFramerate(); // framerate_gui.cpp
2137 if (argc == 0) {
2138 IConsoleHelp("Show frame rate and game speed information");
2139 return true;
2142 ConPrintFramerate();
2143 return true;
2146 DEF_CONSOLE_CMD(ConFramerateWindow)
2148 extern void ShowFramerateWindow();
2150 if (argc == 0) {
2151 IConsoleHelp("Open the frame rate window");
2152 return true;
2155 if (_network_dedicated) {
2156 IConsoleError("Can not open frame rate window on a dedicated server");
2157 return false;
2160 ShowFramerateWindow();
2161 return true;
2164 static void ConDumpRoadTypes()
2166 IConsolePrintF(CC_DEFAULT, " Flags:");
2167 IConsolePrintF(CC_DEFAULT, " c = catenary");
2168 IConsolePrintF(CC_DEFAULT, " l = no level crossings");
2169 IConsolePrintF(CC_DEFAULT, " X = no houses");
2170 IConsolePrintF(CC_DEFAULT, " h = hidden");
2171 IConsolePrintF(CC_DEFAULT, " T = buildable by towns");
2173 std::map<uint32, const GRFFile *> grfs;
2174 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
2175 const RoadTypeInfo *rti = GetRoadTypeInfo(rt);
2176 if (rti->label == 0) continue;
2177 uint32 grfid = 0;
2178 const GRFFile *grf = rti->grffile[ROTSG_GROUND];
2179 if (grf != nullptr) {
2180 grfid = grf->grfid;
2181 grfs.emplace(grfid, grf);
2183 IConsolePrintF(CC_DEFAULT, " %02u %s %c%c%c%c, Flags: %c%c%c%c%c, GRF: %08X, %s",
2184 (uint)rt,
2185 RoadTypeIsTram(rt) ? "Tram" : "Road",
2186 rti->label >> 24, rti->label >> 16, rti->label >> 8, rti->label,
2187 HasBit(rti->flags, ROTF_CATENARY) ? 'c' : '-',
2188 HasBit(rti->flags, ROTF_NO_LEVEL_CROSSING) ? 'l' : '-',
2189 HasBit(rti->flags, ROTF_NO_HOUSES) ? 'X' : '-',
2190 HasBit(rti->flags, ROTF_HIDDEN) ? 'h' : '-',
2191 HasBit(rti->flags, ROTF_TOWN_BUILD) ? 'T' : '-',
2192 BSWAP32(grfid),
2193 GetStringPtr(rti->strings.name)
2196 for (const auto &grf : grfs) {
2197 IConsolePrintF(CC_DEFAULT, " GRF: %08X = %s", BSWAP32(grf.first), grf.second->filename);
2201 static void ConDumpRailTypes()
2203 IConsolePrintF(CC_DEFAULT, " Flags:");
2204 IConsolePrintF(CC_DEFAULT, " c = catenary");
2205 IConsolePrintF(CC_DEFAULT, " l = no level crossings");
2206 IConsolePrintF(CC_DEFAULT, " h = hidden");
2207 IConsolePrintF(CC_DEFAULT, " s = no sprite combine");
2208 IConsolePrintF(CC_DEFAULT, " a = always allow 90 degree turns");
2209 IConsolePrintF(CC_DEFAULT, " d = always disallow 90 degree turns");
2211 std::map<uint32, const GRFFile *> grfs;
2212 for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
2213 const RailtypeInfo *rti = GetRailTypeInfo(rt);
2214 if (rti->label == 0) continue;
2215 uint32 grfid = 0;
2216 const GRFFile *grf = rti->grffile[RTSG_GROUND];
2217 if (grf != nullptr) {
2218 grfid = grf->grfid;
2219 grfs.emplace(grfid, grf);
2221 IConsolePrintF(CC_DEFAULT, " %02u %c%c%c%c, Flags: %c%c%c%c%c%c, GRF: %08X, %s",
2222 (uint)rt,
2223 rti->label >> 24, rti->label >> 16, rti->label >> 8, rti->label,
2224 HasBit(rti->flags, RTF_CATENARY) ? 'c' : '-',
2225 HasBit(rti->flags, RTF_NO_LEVEL_CROSSING) ? 'l' : '-',
2226 HasBit(rti->flags, RTF_HIDDEN) ? 'h' : '-',
2227 HasBit(rti->flags, RTF_NO_SPRITE_COMBINE) ? 's' : '-',
2228 HasBit(rti->flags, RTF_ALLOW_90DEG) ? 'a' : '-',
2229 HasBit(rti->flags, RTF_DISALLOW_90DEG) ? 'd' : '-',
2230 BSWAP32(grfid),
2231 GetStringPtr(rti->strings.name)
2234 for (const auto &grf : grfs) {
2235 IConsolePrintF(CC_DEFAULT, " GRF: %08X = %s", BSWAP32(grf.first), grf.second->filename);
2239 static void ConDumpCargoTypes()
2241 IConsolePrintF(CC_DEFAULT, " Cargo classes:");
2242 IConsolePrintF(CC_DEFAULT, " p = passenger");
2243 IConsolePrintF(CC_DEFAULT, " m = mail");
2244 IConsolePrintF(CC_DEFAULT, " x = express");
2245 IConsolePrintF(CC_DEFAULT, " a = armoured");
2246 IConsolePrintF(CC_DEFAULT, " b = bulk");
2247 IConsolePrintF(CC_DEFAULT, " g = piece goods");
2248 IConsolePrintF(CC_DEFAULT, " l = liquid");
2249 IConsolePrintF(CC_DEFAULT, " r = refrigerated");
2250 IConsolePrintF(CC_DEFAULT, " h = hazardous");
2251 IConsolePrintF(CC_DEFAULT, " c = covered/sheltered");
2252 IConsolePrintF(CC_DEFAULT, " S = special");
2254 std::map<uint32, const GRFFile *> grfs;
2255 for (CargoID i = 0; i < NUM_CARGO; i++) {
2256 const CargoSpec *spec = CargoSpec::Get(i);
2257 if (!spec->IsValid()) continue;
2258 uint32 grfid = 0;
2259 const GRFFile *grf = spec->grffile;
2260 if (grf != nullptr) {
2261 grfid = grf->grfid;
2262 grfs.emplace(grfid, grf);
2264 IConsolePrintF(CC_DEFAULT, " %02u Bit: %2u, Label: %c%c%c%c, Callback mask: 0x%02X, Cargo class: %c%c%c%c%c%c%c%c%c%c%c, GRF: %08X, %s",
2265 (uint)i,
2266 spec->bitnum,
2267 spec->label >> 24, spec->label >> 16, spec->label >> 8, spec->label,
2268 spec->callback_mask,
2269 (spec->classes & CC_PASSENGERS) != 0 ? 'p' : '-',
2270 (spec->classes & CC_MAIL) != 0 ? 'm' : '-',
2271 (spec->classes & CC_EXPRESS) != 0 ? 'x' : '-',
2272 (spec->classes & CC_ARMOURED) != 0 ? 'a' : '-',
2273 (spec->classes & CC_BULK) != 0 ? 'b' : '-',
2274 (spec->classes & CC_PIECE_GOODS) != 0 ? 'g' : '-',
2275 (spec->classes & CC_LIQUID) != 0 ? 'l' : '-',
2276 (spec->classes & CC_REFRIGERATED) != 0 ? 'r' : '-',
2277 (spec->classes & CC_HAZARDOUS) != 0 ? 'h' : '-',
2278 (spec->classes & CC_COVERED) != 0 ? 'c' : '-',
2279 (spec->classes & CC_SPECIAL) != 0 ? 'S' : '-',
2280 BSWAP32(grfid),
2281 GetStringPtr(spec->name)
2284 for (const auto &grf : grfs) {
2285 IConsolePrintF(CC_DEFAULT, " GRF: %08X = %s", BSWAP32(grf.first), grf.second->filename);
2290 DEF_CONSOLE_CMD(ConDumpInfo)
2292 if (argc != 2) {
2293 IConsoleHelp("Dump debugging information.");
2294 IConsoleHelp("Usage: dump_info roadtypes|railtypes|cargotypes");
2295 IConsoleHelp(" Show information about road/tram types, rail types or cargo types.");
2296 return true;
2299 if (strcasecmp(argv[1], "roadtypes") == 0) {
2300 ConDumpRoadTypes();
2301 return true;
2304 if (strcasecmp(argv[1], "railtypes") == 0) {
2305 ConDumpRailTypes();
2306 return true;
2309 if (strcasecmp(argv[1], "cargotypes") == 0) {
2310 ConDumpCargoTypes();
2311 return true;
2314 return false;
2317 /*******************************
2318 * console command registration
2319 *******************************/
2321 void IConsoleStdLibRegister()
2323 IConsoleCmdRegister("debug_level", ConDebugLevel);
2324 IConsoleCmdRegister("echo", ConEcho);
2325 IConsoleCmdRegister("echoc", ConEchoC);
2326 IConsoleCmdRegister("exec", ConExec);
2327 IConsoleCmdRegister("exit", ConExit);
2328 IConsoleCmdRegister("part", ConPart);
2329 IConsoleCmdRegister("help", ConHelp);
2330 IConsoleCmdRegister("info_cmd", ConInfoCmd);
2331 IConsoleCmdRegister("list_cmds", ConListCommands);
2332 IConsoleCmdRegister("list_aliases", ConListAliases);
2333 IConsoleCmdRegister("newgame", ConNewGame);
2334 IConsoleCmdRegister("restart", ConRestart);
2335 IConsoleCmdRegister("reload", ConReload);
2336 IConsoleCmdRegister("getseed", ConGetSeed);
2337 IConsoleCmdRegister("getdate", ConGetDate);
2338 IConsoleCmdRegister("getsysdate", ConGetSysDate);
2339 IConsoleCmdRegister("quit", ConExit);
2340 IConsoleCmdRegister("resetengines", ConResetEngines, ConHookNoNetwork);
2341 IConsoleCmdRegister("reset_enginepool", ConResetEnginePool, ConHookNoNetwork);
2342 IConsoleCmdRegister("return", ConReturn);
2343 IConsoleCmdRegister("screenshot", ConScreenShot);
2344 IConsoleCmdRegister("script", ConScript);
2345 IConsoleCmdRegister("scrollto", ConScrollToTile);
2346 IConsoleCmdRegister("alias", ConAlias);
2347 IConsoleCmdRegister("load", ConLoad);
2348 IConsoleCmdRegister("rm", ConRemove);
2349 IConsoleCmdRegister("save", ConSave);
2350 IConsoleCmdRegister("saveconfig", ConSaveConfig);
2351 IConsoleCmdRegister("ls", ConListFiles);
2352 IConsoleCmdRegister("cd", ConChangeDirectory);
2353 IConsoleCmdRegister("pwd", ConPrintWorkingDirectory);
2354 IConsoleCmdRegister("clear", ConClearBuffer);
2355 IConsoleCmdRegister("setting", ConSetting);
2356 IConsoleCmdRegister("setting_newgame", ConSettingNewgame);
2357 IConsoleCmdRegister("list_settings",ConListSettings);
2358 IConsoleCmdRegister("gamelog", ConGamelogPrint);
2359 IConsoleCmdRegister("rescan_newgrf", ConRescanNewGRF);
2361 IConsoleAliasRegister("dir", "ls");
2362 IConsoleAliasRegister("del", "rm %+");
2363 IConsoleAliasRegister("newmap", "newgame");
2364 IConsoleAliasRegister("patch", "setting %+");
2365 IConsoleAliasRegister("set", "setting %+");
2366 IConsoleAliasRegister("set_newgame", "setting_newgame %+");
2367 IConsoleAliasRegister("list_patches", "list_settings %+");
2368 IConsoleAliasRegister("developer", "setting developer %+");
2370 IConsoleCmdRegister("list_ai_libs", ConListAILibs);
2371 IConsoleCmdRegister("list_ai", ConListAI);
2372 IConsoleCmdRegister("reload_ai", ConReloadAI);
2373 IConsoleCmdRegister("rescan_ai", ConRescanAI);
2374 IConsoleCmdRegister("start_ai", ConStartAI);
2375 IConsoleCmdRegister("stop_ai", ConStopAI);
2377 IConsoleCmdRegister("list_game", ConListGame);
2378 IConsoleCmdRegister("list_game_libs", ConListGameLibs);
2379 IConsoleCmdRegister("rescan_game", ConRescanGame);
2381 IConsoleCmdRegister("companies", ConCompanies);
2382 IConsoleAliasRegister("players", "companies");
2384 /* networking functions */
2386 /* Content downloading is only available with ZLIB */
2387 #if defined(WITH_ZLIB)
2388 IConsoleCmdRegister("content", ConContent);
2389 #endif /* defined(WITH_ZLIB) */
2391 /*** Networking commands ***/
2392 IConsoleCmdRegister("say", ConSay, ConHookNeedNetwork);
2393 IConsoleCmdRegister("say_company", ConSayCompany, ConHookNeedNetwork);
2394 IConsoleAliasRegister("say_player", "say_company %+");
2395 IConsoleCmdRegister("say_client", ConSayClient, ConHookNeedNetwork);
2397 IConsoleCmdRegister("connect", ConNetworkConnect, ConHookClientOnly);
2398 IConsoleCmdRegister("clients", ConNetworkClients, ConHookNeedNetwork);
2399 IConsoleCmdRegister("status", ConStatus, ConHookServerOnly);
2400 IConsoleCmdRegister("server_info", ConServerInfo, ConHookServerOnly);
2401 IConsoleAliasRegister("info", "server_info");
2402 IConsoleCmdRegister("reconnect", ConNetworkReconnect, ConHookClientOnly);
2403 IConsoleCmdRegister("rcon", ConRcon, ConHookNeedNetwork);
2405 IConsoleCmdRegister("join", ConJoinCompany, ConHookNeedNetwork);
2406 IConsoleAliasRegister("spectate", "join 255");
2407 IConsoleCmdRegister("move", ConMoveClient, ConHookServerOnly);
2408 IConsoleCmdRegister("reset_company", ConResetCompany, ConHookServerOnly);
2409 IConsoleAliasRegister("clean_company", "reset_company %A");
2410 IConsoleCmdRegister("client_name", ConClientNickChange, ConHookServerOnly);
2411 IConsoleCmdRegister("kick", ConKick, ConHookServerOnly);
2412 IConsoleCmdRegister("ban", ConBan, ConHookServerOnly);
2413 IConsoleCmdRegister("unban", ConUnBan, ConHookServerOnly);
2414 IConsoleCmdRegister("banlist", ConBanList, ConHookServerOnly);
2416 IConsoleCmdRegister("pause", ConPauseGame, ConHookServerOnly);
2417 IConsoleCmdRegister("unpause", ConUnpauseGame, ConHookServerOnly);
2419 IConsoleCmdRegister("company_pw", ConCompanyPassword, ConHookNeedNetwork);
2420 IConsoleAliasRegister("company_password", "company_pw %+");
2422 IConsoleAliasRegister("net_frame_freq", "setting frame_freq %+");
2423 IConsoleAliasRegister("net_sync_freq", "setting sync_freq %+");
2424 IConsoleAliasRegister("server_pw", "setting server_password %+");
2425 IConsoleAliasRegister("server_password", "setting server_password %+");
2426 IConsoleAliasRegister("rcon_pw", "setting rcon_password %+");
2427 IConsoleAliasRegister("rcon_password", "setting rcon_password %+");
2428 IConsoleAliasRegister("name", "setting client_name %+");
2429 IConsoleAliasRegister("server_name", "setting server_name %+");
2430 IConsoleAliasRegister("server_port", "setting server_port %+");
2431 IConsoleAliasRegister("server_advertise", "setting server_advertise %+");
2432 IConsoleAliasRegister("max_clients", "setting max_clients %+");
2433 IConsoleAliasRegister("max_companies", "setting max_companies %+");
2434 IConsoleAliasRegister("max_spectators", "setting max_spectators %+");
2435 IConsoleAliasRegister("max_join_time", "setting max_join_time %+");
2436 IConsoleAliasRegister("pause_on_join", "setting pause_on_join %+");
2437 IConsoleAliasRegister("autoclean_companies", "setting autoclean_companies %+");
2438 IConsoleAliasRegister("autoclean_protected", "setting autoclean_protected %+");
2439 IConsoleAliasRegister("autoclean_unprotected", "setting autoclean_unprotected %+");
2440 IConsoleAliasRegister("restart_game_year", "setting restart_game_year %+");
2441 IConsoleAliasRegister("min_players", "setting min_active_clients %+");
2442 IConsoleAliasRegister("reload_cfg", "setting reload_cfg %+");
2444 /* debugging stuff */
2445 #ifdef _DEBUG
2446 IConsoleDebugLibRegister();
2447 #endif
2448 IConsoleCmdRegister("fps", ConFramerate);
2449 IConsoleCmdRegister("fps_wnd", ConFramerateWindow);
2451 /* NewGRF development stuff */
2452 IConsoleCmdRegister("reload_newgrfs", ConNewGRFReload, ConHookNewGRFDeveloperTool);
2453 IConsoleCmdRegister("newgrf_profile", ConNewGRFProfile, ConHookNewGRFDeveloperTool);
2455 IConsoleCmdRegister("dump_info", ConDumpInfo);