OpenTTD Source 20261112-master-gbcbec5e63f
command.cpp
Go to the documentation of this file.
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "landscape.h"
12#include "error.h"
13#include "gui.h"
14#include "command_func.h"
15#include "network/network.h"
16#include "genworld.h"
17#include "strings_func.h"
18#include "texteff.hpp"
19#include "town.h"
21#include "company_func.h"
22#include "company_base.h"
23#include "signal_func.h"
24#include "core/backup_type.hpp"
25#include "object_base.h"
26#include "autoreplace_cmd.h"
27#include "company_cmd.h"
28#include "depot_cmd.h"
29#include "economy_cmd.h"
30#include "engine_cmd.h"
31#include "goal_cmd.h"
32#include "group_cmd.h"
33#include "industry_cmd.h"
34#include "league_cmd.h"
35#include "landscape_cmd.h"
36#include "misc_cmd.h"
37#include "news_cmd.h"
38#include "object_cmd.h"
39#include "order_cmd.h"
40#include "rail_cmd.h"
41#include "road_cmd.h"
42#include "roadveh_cmd.h"
43#include "settings_cmd.h"
44#include "signs_cmd.h"
45#include "station_cmd.h"
46#include "story_cmd.h"
47#include "subsidy_cmd.h"
48#include "terraform_cmd.h"
49#include "timetable_cmd.h"
50#include "town_cmd.h"
51#include "train_cmd.h"
52#include "tree_cmd.h"
53#include "tunnelbridge_cmd.h"
54#include "vehicle_cmd.h"
55#include "viewport_cmd.h"
56#include "water_cmd.h"
57#include "waypoint_cmd.h"
59#include "string_func.h"
60
61#include "table/strings.h"
62
63#include "safeguards.h"
64
65
67
68
76 std::string_view name;
79};
80/* Helpers to generate the master command table from the command traits. */
81template <typename T>
82constexpr CommandInfo CommandFromTrait() noexcept { return { T::name, T::flags, T::type }; };
83
84template <typename T, T... i>
85constexpr auto MakeCommandsFromTraits(std::integer_sequence<T, i...>) noexcept {
86 return EnumIndexArray<CommandInfo, Commands, static_cast<Commands>(sizeof...(i))>{{{ CommandFromTrait<CommandTraits<static_cast<Commands>(i)>>()... }}};
87}
88
94static constexpr auto _command_table = MakeCommandsFromTraits(std::make_integer_sequence<std::underlying_type_t<Commands>, to_underlying(Commands::End)>{});
95
96
103{
104 return to_underlying(cmd) < _command_table.size();
105}
106
113{
114 assert(IsValidCommand(cmd));
115
116 return _command_table[cmd].flags;
117}
118
124std::string_view GetCommandName(Commands cmd)
125{
126 assert(IsValidCommand(cmd));
127
128 return _command_table[cmd].name;
129}
130
137{
138 /* Lookup table for the command types that are allowed for a given pause level setting. */
139 static constexpr CommandPauseLevel command_type_lookup[] = {
140 CommandPauseLevel::AllActions, // CommandType::LandscapeConstruction
141 CommandPauseLevel::NoLandscaping, // CommandType::VehicleConstruction
142 CommandPauseLevel::NoLandscaping, // CommandType::MoneyManagement
143 CommandPauseLevel::NoConstruction, // CommandType::VehicleManagement
144 CommandPauseLevel::NoConstruction, // CommandType::RouteManagement
145 CommandPauseLevel::NoConstruction, // CommandType::OtherManagement
146 CommandPauseLevel::NoActions, // CommandType::CompanySetting
147 CommandPauseLevel::NoActions, // CommandType::ServerSetting
148 CommandPauseLevel::NoActions, // CommandType::Cheat
149 };
150 static_assert(std::size(command_type_lookup) == to_underlying(CommandType::End));
151
152 assert(IsValidCommand(cmd));
153 return _game_mode == GameMode::Editor || command_type_lookup[to_underlying(_command_table[cmd].type)] <= _settings_game.construction.command_pause_level;
154}
155
161void CommandHelperBase::InternalDoBefore(bool top_level, bool test)
162{
163 if (top_level) _cleared_object_areas.clear();
164 if (test) SetTownRatingTestMode(true);
165}
166
174void CommandHelperBase::InternalDoAfter(CommandCost &res, DoCommandFlags flags, bool top_level, bool test)
175{
176 if (test) {
178
179 if (res.Succeeded() && top_level && !flags.Test(DoCommandFlag::QueryCost) && !flags.Test(DoCommandFlag::Bankrupt)) {
180 CheckCompanyHasMoney(res); // CheckCompanyHasMoney() modifies 'res' to an error if it fails.
181 }
182 } else {
183 /* If top-level, subtract the money. */
184 if (res.Succeeded() && top_level && !flags.Test(DoCommandFlag::Bankrupt)) {
186 }
187 }
188}
189
199std::tuple<bool, bool, bool> CommandHelperBase::InternalPostBefore(Commands cmd, CommandFlags flags, TileIndex tile, StringID err_message, bool network_command)
200{
201 /* Cost estimation is generally only done when the
202 * local user presses shift while doing something.
203 * However, in case of incoming network commands,
204 * map generation or the pause button we do want
205 * to execute. */
206 bool estimate_only = IsShiftPressed() && IsLocalCompany() && !_generating_world && !network_command && !flags.Test(CommandFlag::NoEst);
207
208 /* We're only sending the command, so don't do
209 * fancy things for 'success'. */
210 bool only_sending = _networking && !network_command;
211
212 if (_pause_mode.Any() && !IsCommandAllowedWhilePaused(cmd) && !estimate_only) {
213 ShowErrorMessage(GetEncodedString(err_message), GetEncodedString(STR_ERROR_NOT_ALLOWED_WHILE_PAUSED),
215 return { true, estimate_only, only_sending };
216 } else {
217 return { false, estimate_only, only_sending };
218 }
219}
220
230void CommandHelperBase::InternalPostResult(CommandCost &res, TileIndex tile, bool estimate_only, bool only_sending, StringID err_message, bool my_cmd)
231{
232 int x = TileX(tile) * TILE_SIZE;
233 int y = TileY(tile) * TILE_SIZE;
234
235 if (res.Failed()) {
236 /* Only show the error when it's for us. */
237 if (estimate_only || (IsLocalCompany() && err_message != 0 && my_cmd)) {
238 ShowErrorMessage(GetEncodedString(err_message), x, y, res);
239 }
240 } else if (estimate_only) {
242 } else if (!only_sending && tile != 0 && IsLocalCompany() && _game_mode != GameMode::Editor) {
243 /* Only show the cost animation when we did actually
244 * execute the command, i.e. we're not sending it to
245 * the server, when it has cost the local company
246 * something. Furthermore in the editor there is no
247 * concept of cost, so don't show it there either. */
249 }
250}
251
259void CommandHelperBase::LogCommandExecution(Commands cmd, StringID err_message, const CommandDataBuffer &args, bool failed)
260{
261 Debug(Facility::Desync, Severity::Error, "{}: {:08x}; {:02x}; {:02x}; {:08x}; {:08x}; {} ({})", failed ? "cmdf" : "cmd", (uint32_t)TimerGameEconomy::date.base(), TimerGameEconomy::date_fract, _current_company, cmd, err_message, FormatArrayAsHex(args), GetCommandName(cmd));
262}
263
271{
272 /* Always execute server and spectator commands as spectator */
273 bool exec_as_spectator = cmd_flags.Any({CommandFlag::Spectator, CommandFlag::Server});
274
275 /* If the company isn't valid it may only do server command or start a new company!
276 * The server will ditch any server commands a client sends to it, so effectively
277 * this guards the server from executing functions for an invalid company. */
278 if (_game_mode == GameMode::Normal && !exec_as_spectator && !Company::IsValidID(_current_company) && !(_current_company == OWNER_DEITY && cmd_flags.Test(CommandFlag::Deity))) {
279 return false;
280 }
281
282 if (exec_as_spectator) cur_company.Change(COMPANY_SPECTATOR);
283
284 /* Enter test mode. */
285 _cleared_object_areas.clear();
288 return true;
289}
290
300std::tuple<bool, bool, bool> CommandHelperBase::InternalExecuteValidateTestAndPrepExec(CommandCost &res, CommandFlags cmd_flags, bool estimate_only, bool network_command, [[maybe_unused]] Backup<CompanyID> &cur_company)
301{
304
305 /* Make sure we're not messing things up here. */
306 assert(cmd_flags.Any({CommandFlag::Spectator, CommandFlag::Server}) ? _current_company == COMPANY_SPECTATOR : cur_company.Verify());
307
308 /* If the command fails, we're doing an estimate
309 * or the player does not have enough money
310 * (unless it's a command where the test and
311 * execution phase might return different costs)
312 * we bail out here. */
313 bool test_and_exec_can_differ = cmd_flags.Test(CommandFlag::NoTest);
314 if (res.Failed() || estimate_only || (!test_and_exec_can_differ && !CheckCompanyHasMoney(res))) {
315 return { true, !_networking || _generating_world || network_command, false };
316 }
317
318 bool send_net = _networking && !_generating_world && !network_command;
319
320 if (!send_net) {
321 /* Prepare for command execution. */
322 _cleared_object_areas.clear();
324 }
325
326 return { false, IsVisibleSeverity(Facility::Desync, Severity::Error), send_net };
327}
328
340CommandCost CommandHelperBase::InternalExecuteProcessResult(Commands cmd, CommandFlags cmd_flags, [[maybe_unused]] const CommandCost &res_test, const CommandCost &res_exec, Money extra_cash, TileIndex tile, Backup<CompanyID> &cur_company)
341{
343
344 if (cmd == Commands::CompanyControl) {
345 cur_company.Trash();
346 /* We are a new company -> Switch to new local company.
347 * We were closed down -> Switch to spectator
348 * Some other company opened/closed down -> The outside function will switch back */
350 } else {
351 /* Make sure nothing bad happened, like changing the current company. */
352 assert(cmd_flags.Any({CommandFlag::Spectator, CommandFlag::Server}) ? _current_company == COMPANY_SPECTATOR : cur_company.Verify());
353 cur_company.Restore();
354 }
355
356 /* If the test and execution can differ we have to check the
357 * return of the command. Otherwise we can check whether the
358 * test and execution have yielded the same result,
359 * i.e. cost and error state are the same. */
360 bool test_and_exec_can_differ = cmd_flags.Test(CommandFlag::NoTest);
361 if (!test_and_exec_can_differ) {
362 assert(res_test.GetCost() == res_exec.GetCost() && res_test.Failed() == res_exec.Failed()); // sanity check
363 } else if (res_exec.Failed()) {
364 return res_exec;
365 }
366
367 /* If we're needing more money and we haven't done
368 * anything yet, ask for the money! */
369 if (extra_cash != 0 && res_exec.GetCost() == 0) {
370 /* It could happen we removed rail, thus gained money, and deleted something else.
371 * So make sure the signal buffer is empty even in this case */
373 return CommandCostWithParam(STR_ERROR_NOT_ENOUGH_CASH_REQUIRES_CURRENCY, extra_cash);
374 }
375
376 /* update last build coordinate of company. */
377 if (tile != 0) {
379 if (c != nullptr) c->last_build_coordinate = tile;
380 }
381
383
384 /* Record if there was a command issues during pause; ignore pause/other setting related changes. */
386
387 /* update signals if needed */
389
390 return res_exec;
391}
392
393
400{
401 this->AddCost(ret.cost);
402 if (this->success && !ret.success) {
403 this->message = ret.message;
404 this->encoded_message = std::move(ret.encoded_message);
405 this->success = false;
406 }
407}
408
416{
417 CommandCost error = CommandCost(str);
418 if (IsLocalCompany()) {
419 error.SetEncodedMessage(GetEncodedString(str, value));
420 }
421 return error;
422}
Command definitions related to autoreplace.
Class for backupping variables and making sure they are restored later.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
Common return value for all commands.
bool Succeeded() const
Did this command succeed?
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Money GetCost() const
The costs as made up to this moment.
void SetEncodedMessage(EncodedString &&message)
Set the encoded message string.
StringID message
Warning message for when success is unset.
bool Failed() const
Did this command fail?
CommandCost()
Creates a command cost return with no cost and no error.
bool success
Whether the command went fine up to this moment.
EncodedString encoded_message
Encoded error message, used if the error message includes parameters.
static std::tuple< bool, bool, bool > InternalPostBefore(Commands cmd, CommandFlags flags, TileIndex tile, StringID err_message, bool network_command)
Decide what to do with the command depending on current game state.
Definition command.cpp:199
static void InternalPostResult(CommandCost &res, TileIndex tile, bool estimate_only, bool only_sending, StringID err_message, bool my_cmd)
Process result of executing a command, possibly displaying any error to the player.
Definition command.cpp:230
static void InternalDoBefore(bool top_level, bool test)
Prepare for calling a command proc.
Definition command.cpp:161
static void LogCommandExecution(Commands cmd, StringID err_message, const CommandDataBuffer &args, bool failed)
Helper to make a desync log for a command.
Definition command.cpp:259
static CommandCost InternalExecuteProcessResult(Commands cmd, CommandFlags cmd_flags, const CommandCost &res_test, const CommandCost &res_exec, Money extra_cash, TileIndex tile, Backup< CompanyID > &cur_company)
Process the result of a command test run and execution run.
Definition command.cpp:340
static bool InternalExecutePrepTest(CommandFlags cmd_flags, Backup< CompanyID > &cur_company)
Prepare for the test run of a command proc call.
Definition command.cpp:270
static void InternalDoAfter(CommandCost &res, DoCommandFlags flags, bool top_level, bool test)
Process result after calling a command proc.
Definition command.cpp:174
static std::tuple< bool, bool, bool > InternalExecuteValidateTestAndPrepExec(CommandCost &res, CommandFlags cmd_flags, bool estimate_only, bool network_command, Backup< CompanyID > &cur_company)
Validate result of test run and prepare for real execution.
Definition command.cpp:300
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
CommandFlags GetCommandFlags(Commands cmd)
Get the command flags associated with the given command.
Definition command.cpp:112
CommandCost CommandCostWithParam(StringID str, uint64_t value)
Return an error status, with string and parameter.
Definition command.cpp:415
bool IsCommandAllowedWhilePaused(Commands cmd)
Returns whether the command is allowed while the game is paused.
Definition command.cpp:136
static constexpr auto _command_table
The master command table.
Definition command.cpp:94
std::string_view GetCommandName(Commands cmd)
Get the name of the given command.
Definition command.cpp:124
bool IsValidCommand(Commands cmd)
This function range-checks a Commands.
Definition command.cpp:102
Functions related to commands.
bool IsCommandAllowedWhilePaused(Commands cmd)
Returns whether the command is allowed while the game is paused.
Definition command.cpp:136
std::string_view GetCommandName(Commands cmd)
Get the name of the given command.
Definition command.cpp:124
CommandType
Types of commands we have.
@ End
End marker.
@ ServerSetting
Pausing/removing companies/server settings.
@ QueryCost
query cost only, don't build.
@ Bankrupt
company bankrupts, skip money check, skip vehicle on tile check in some cases
@ NoEst
the command is never estimated.
@ Deity
the command may be executed by COMPANY_DEITY
@ Spectator
the command may be initiated by a spectator
@ Server
the command can only be initiated by the server
@ NoTest
the command's output may differ between test and execute due to town rating changes etc.
CommandPauseLevel
Different command pause levels.
@ NoLandscaping
No landscaping actions may be executed.
@ NoConstruction
No construction actions may be executed.
@ NoActions
No user actions may be executed.
@ AllActions
All actions may be executed.
std::vector< uint8_t > CommandDataBuffer
Storage buffer for serialized command data.
EnumBitSet< CommandFlag, uint16_t > CommandFlags
Bitset of CommandFlag elements.
Commands
List of commands.
@ CompanyControl
used in multiplayer to create a new companies etc.
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
bool CheckCompanyHasMoney(CommandCost &cost)
Verify whether the company can pay the bill.
static void SubtractMoneyFromCompany(Company *c, const CommandCost &cost)
Deduct costs of a command from the money of a company.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
CompanyID _current_company
Company currently doing an action.
Command definitions related to companies.
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
static constexpr Owner OWNER_DEITY
The object is owned by a superuser / goal script.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
bool IsVisibleSeverity(Facility facility, Severity severity)
Test if debug severity is visible for the given facility.
Definition debug.h:24
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Desync
Desync message facility.
Definition debug_type.h:41
@ Error
Error, but we are recovering.
Definition debug_type.h:16
Command definitions related to depots.
Command definitions related to the economy.
Endian-aware buffer.
Command definitions related to engines.
#define T
Climate temperate.
Definition engines.h:91
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Functions related to errors.
@ Info
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition error.h:22
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
bool _generating_world
Whether we are generating the map or not.
Definition genworld.cpp:70
Functions related to world/map generation.
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:46
bool IsShiftPressed()
Test if the shift key is pressed.
Definition gfx_func.h:88
Command definitions related to goals.
Command definitions related to engine groups.
GUI functions that shouldn't be here.
void ShowEstimatedCostOrIncome(Money cost, int x, int y)
Display estimated costs.
Definition misc_gui.cpp:490
Command definitions related to industries.
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
Functions related to OTTD's landscape.
Command definitions related to landscape (slopes etc.).
Command definitions related to league tables.
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
Miscellaneous command definitions.
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Definition misc_gui.cpp:508
bool _networking
are we in networking mode?
Definition network.cpp:63
Basic functions/variables used all over the place.
@ PSM_LEAVE_TESTMODE
Leave command test mode, revert to previous mode.
@ PSM_LEAVE_COMMAND
Leave command scope, revert to previous mode.
@ PSM_ENTER_COMMAND
Enter command scope, changes will be permanent.
@ PSM_ENTER_TESTMODE
Enter command test mode, changes will be temporary.
Command definitions related to news messages.
Base for all objects.
Command definitions related to objects.
@ CommandDuringPause
A game paused, and a command executed during the pause; resets on autosave.
Definition openttd.h:79
@ Editor
In the scenario editor.
Definition openttd.h:21
@ Normal
Playing a game.
Definition openttd.h:20
Command definitions related to orders.
Command definitions for rail.
Road related functions.
Command definitions related to road vehicles.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
Command definitions related to settings.
void UpdateSignalsInBuffer()
Update signals in buffer Called from 'outside'.
Definition signal.cpp:581
Functions related to signals.
Command definitions related to signs.
Command definitions related to stations.
Definition of base types and functions in a cross-platform compatible way.
Command definitions related to stories.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:76
Functions related to low-level strings.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
Class to backup a specific variable and restore it later.
void Trash()
Trash the backup.
bool Verify() const
Check whether the variable is currently equals the backup.
void Change(const U &new_value)
Change the value of the variable.
void Restore()
Restore the variable.
static void SwitchMode(PersistentStorageMode mode, bool ignore_prev_mode=false)
Clear temporary changes made since the last call to SwitchMode, and set whether subsequent changes sh...
Define a command with the flags which belongs to it.
Definition command.cpp:75
CommandType type
The type of command.
Definition command.cpp:78
std::string_view name
A human readable name for the procedure.
Definition command.cpp:76
CommandFlags flags
The (command) flags to that apply to this command.
Definition command.cpp:77
TileIndex last_build_coordinate
Coordinate of the last build thing by this company.
static Company * GetIfValid(auto index)
static int _counter
Number of instances of this class.
Command definitions related to subsidies.
Command definitions related to terraforming.
Functions related to text effects.
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
Definition of the game-economy-timer.
Command definitions related to timetables.
Base of the town class.
void SetTownRatingTestMode(bool mode)
Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings...
Command definitions related to towns.
Command definitions related to trains.
Command definitions related to tree tiles.
Command definitions related to tunnels and bridges.
Command definitions for vehicles.
Command definitions related to viewports.
Command definitions related to water tiles.
Command definitions related to waypoints.