OpenTTD Source 20260206-master-g4d4e37dbf1
command_type.h
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#ifndef COMMAND_TYPE_H
11#define COMMAND_TYPE_H
12
13#include "company_type.h"
14#include "economy_type.h"
15#include "strings_type.h"
16#include "tile_type.h"
17
18struct GRFFile;
19
25 Money cost;
28 bool success;
29 Owner owner = CompanyID::Invalid();
32
33public:
38
44 explicit CommandCost(StringID msg, StringID extra_msg = INVALID_STRING_ID) : cost(0), message(msg), expense_type(INVALID_EXPENSES), success(false), extra_message(extra_msg) {}
45
51
57 CommandCost(ExpensesType ex_t, const Money &cst) : cost(cst), message(INVALID_STRING_ID), expense_type(ex_t), success(true) {}
58
64 inline void SetErrorOwner(Owner owner)
65 {
66 this->owner = owner;
67 }
68
76 {
77 this->encoded_message = std::move(message);
78 }
79
85 {
86 return this->encoded_message;
87 }
88
93 inline CompanyID GetErrorOwner() const
94 {
95 return this->owner;
96 }
97
102 inline void AddCost(const Money &cost)
103 {
104 this->cost += cost;
105 }
106
107 void AddCost(CommandCost &&cmd_cost);
108
113 inline void MultiplyCost(int factor)
114 {
115 this->cost *= factor;
116 }
117
122 inline Money GetCost() const
123 {
124 return this->cost;
125 }
126
132 {
133 return this->expense_type;
134 }
135
141 {
142 assert(message != INVALID_STRING_ID);
143 this->success = false;
144 this->message = message;
145 this->extra_message = INVALID_STRING_ID;
146 }
147
153 {
154 if (this->success) return INVALID_STRING_ID;
155 return this->message;
156 }
157
163 {
164 if (this->success) return INVALID_STRING_ID;
165 return this->extra_message;
166 }
167
172 inline bool Succeeded() const
173 {
174 return this->success;
175 }
176
181 inline bool Failed() const
182 {
183 return !this->success;
184 }
185};
186
187CommandCost CommandCostWithParam(StringID str, uint64_t value);
188CommandCost CommandCostWithParam(StringID str, ConvertibleThroughBase auto value) { return CommandCostWithParam(str, value.base()); }
189
200enum class Commands : uint8_t {
215
218
223
226
234
236
238
241
243
249
253
259
261
267
270
274
277
285
289
291
293
295
303 ExpandTown,
307
311
315
338
340
342
345
349
351
358
367
374
376
382
384};
385
404using DoCommandFlags = EnumBitSet<DoCommandFlag, uint16_t>;
405
425using CommandFlags = EnumBitSet<CommandFlag, uint16_t>;
426
441
443
450
451
452template <typename T> struct CommandFunctionTraitHelper;
453template <typename... Targs>
454struct CommandFunctionTraitHelper<CommandCost(*)(DoCommandFlags, Targs...)> {
455 using Args = std::tuple<std::decay_t<Targs>...>;
456 using RetTypes = void;
457 using CbArgs = Args;
458 using CbProcType = void(*)(Commands, const CommandCost &);
459};
460template <template <typename...> typename Tret, typename... Tretargs, typename... Targs>
461struct CommandFunctionTraitHelper<Tret<CommandCost, Tretargs...>(*)(DoCommandFlags, Targs...)> {
462 using Args = std::tuple<std::decay_t<Targs>...>;
463 using RetTypes = std::tuple<std::decay_t<Tretargs>...>;
464 using CbArgs = std::tuple<std::decay_t<Tretargs>..., std::decay_t<Targs>...>;
465 using CbProcType = void(*)(Commands, const CommandCost &, Tretargs...);
466};
467
469template <Commands Tcmd> struct CommandTraits;
470
471#define DEF_CMD_TRAIT(cmd_, proc_, flags_, type_) \
472 template <> struct CommandTraits<cmd_> { \
473 using ProcType = decltype(&proc_); \
474 using Args = typename CommandFunctionTraitHelper<ProcType>::Args; \
475 using RetTypes = typename CommandFunctionTraitHelper<ProcType>::RetTypes; \
476 using CbArgs = typename CommandFunctionTraitHelper<ProcType>::CbArgs; \
477 using RetCallbackProc = typename CommandFunctionTraitHelper<ProcType>::CbProcType; \
478 static constexpr Commands cmd = cmd_; \
479 static constexpr auto &proc = proc_; \
480 static constexpr CommandFlags flags = flags_; \
481 static constexpr CommandType type = type_; \
482 static inline constexpr std::string_view name = #proc_; \
483 };
484
486typedef std::vector<uint8_t> CommandDataBuffer;
487
497typedef void CommandCallback(Commands cmd, const CommandCost &result, TileIndex tile);
498
509typedef void CommandCallbackData(Commands cmd, const CommandCost &result, const CommandDataBuffer &data, CommandDataBuffer result_data);
510
511#endif /* COMMAND_TYPE_H */
Common return value for all commands.
ExpensesType GetExpensesType() const
The expense type of the cost.
bool Succeeded() const
Did this command succeed?
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
void MakeError(StringID message)
Makes this CommandCost behave like an error command.
Money cost
The cost of this action.
StringID extra_message
Additional warning message for when success is unset.
CommandCost(ExpensesType ex_t, const Money &cst)
Creates a command return value with the given start cost and expense type.
Money GetCost() const
The costs as made up to this moment.
CommandCost(ExpensesType ex_t)
Creates a command cost with given expense type and start cost of 0.
void SetEncodedMessage(EncodedString &&message)
Set the encoded message string.
Owner owner
Originator owner of error.
CommandCost(StringID msg, StringID extra_msg=INVALID_STRING_ID)
Creates a command return value with one, or optionally two, error message strings.
StringID message
Warning message for when success is unset.
bool Failed() const
Did this command fail?
EncodedString & GetEncodedMessage()
Get the last encoded error message.
CommandCost()
Creates a command cost return with no cost and no error.
void MultiplyCost(int factor)
Multiplies the cost of the command by the given factor.
StringID GetErrorMessage() const
Returns the error message of a command.
void SetErrorOwner(Owner owner)
Set the 'owner' (the originator) of this error message.
bool success
Whether the command went fine up to this moment.
CompanyID GetErrorOwner() const
Get the originator owner for this error.
ExpensesType expense_type
the type of expense as shown on the finances view
StringID GetExtraErrorMessage() const
Returns the extra error message of a command.
EncodedString encoded_message
Encoded error message, used if the error message includes parameters.
Container for an encoded string, created by GetEncodedString.
Enum-as-bit-set wrapper.
CommandType
Types of commands we have.
@ VehicleConstruction
Construction, modification (incl. refit) and destruction of vehicles.
@ RouteManagement
Modifications to route management (orders, groups, etc).
@ OtherManagement
Renaming stuff, changing company colours, placing signs, etc.
@ LandscapeConstruction
Construction and destruction of objects on the map.
@ MoneyManagement
Management of money, i.e. loans.
@ CompanySetting
Changing settings related to a company.
@ VehicleManagement
Stopping, starting, sending to depot, turning around, replace orders etc.
@ ServerSetting
Pausing/removing companies/server settings.
void CommandCallback(Commands cmd, const CommandCost &result, TileIndex tile)
Define a callback function for the client, after the command is finished.
DoCommandFlag
List of flags for a command.
@ Auto
don't allow building on structures
@ QueryCost
query cost only, don't build.
@ NoModifyTownRating
do not change town rating
@ NoWater
don't allow building on water
@ Execute
execute the given command
@ Bankrupt
company bankrupts, skip money check, skip vehicle on tile check in some cases
@ AllTiles
allow this command also on TileType::Void tiles
@ NoCargoCapacityCheck
when autoreplace/autorenew is in progress, this shall prevent truncating the amount of cargo in the v...
@ ForceClearTile
do not only remove the object on the tile, but also clear any water left on it
@ AutoReplace
autoreplace/autorenew is in progress, this shall disable vehicle limits when building,...
@ NoTestTownRating
town rating does not disallow you from building
CommandCost CommandCostWithParam(StringID str, uint64_t value)
Return an error status, with string and parameter.
Definition command.cpp:416
CommandFlag
Command flags for the command table _command_proc_table.
@ NoEst
the command is never estimated.
@ Deity
the command may be executed by COMPANY_DEITY
@ Spectator
the command may be initiated by a spectator
@ Offline
the command cannot be executed in a multiplayer game; single-player only
@ Server
the command can only be initiated by the server
@ StrCtrl
the command's string may contain control strings
@ Location
the command has implicit location argument.
@ 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.
void CommandCallbackData(Commands cmd, const CommandCost &result, const CommandDataBuffer &data, CommandDataBuffer result_data)
Define a callback function for the client, after the command is finished.
std::vector< uint8_t > CommandDataBuffer
Storage buffer for serialized command data.
Commands
List of commands.
@ RenameDepot
rename a depot
@ ForceTrainProceed
proceed a train to pass a red signal
@ ClearArea
clear an area
@ TownGrowthRate
set the town growth rate
@ SetStoryPageTitle
update title of a story page
@ BuildRailWaypoint
build a waypoint
@ SendVehicleToDepot
send a vehicle to a depot
@ PlaceHouseArea
place an area of houses
@ TownCargoGoal
set the goal of a cargo for a town
@ MoveOrder
move an order
@ Pause
pause the game
@ IndustrySetProduction
change industry production
@ CreateGoal
create a new goal
@ DepotMassAutoreplace
force the autoreplace to take action in a given depot
@ AutofillTimetable
autofill the timetable
@ RemoveGoal
remove a goal
@ CloneOrder
clone (and share) an order
@ BuildAirport
build an airport
@ ChangeServiceInterval
change the server interval of a vehicle
@ MoveStationName
move a station name
@ SetTimetableStart
set the date that a timetable should start
@ WantEnginePreview
confirm the preview of an engine
@ PlantTree
plant a tree
@ DecreaseLoan
decrease the loan from the bank
@ GoalQuestion
ask a goal related question
@ BuildRoadDepot
build a road depot
@ PlaceSign
place a sign
@ SetCompanyManagerFace
set the manager's face of the company
@ OrderRefit
change the refit information of an order (for "goto depot" )
@ ShowStoryPage
show a story page
@ SetGroupLivery
set the livery for a group
@ ScrollViewport
scroll main viewport of players
@ SetGoalDestination
update goal destination of a goal
@ BuildSignal
build a signal
@ IndustrySetText
change additional text for the industry
@ ChangeTimetableBulk
change the timetable for all orders of a vehicle
@ IndustrySetFlags
change industry control flags
@ UpdateLeagueTableElementData
update the data fields of a league table element
@ ConvertRoad
convert a road type
@ UpdateLeagueTableElementScore
update the score of a league table element
@ RenameStation
rename a station
@ RemoveRoadLong
remove a complete road (not a "half" one)
@ MoneyCheat
do the money cheat
@ ConvertRail
convert a rail type
@ ClearOrderBackup
clear the order backup of a given user/tile
@ ChangeSetting
change a setting
@ SellVehicle
sell a vehicle
@ GoalQuestionAnswer
answer(s) to Commands::GoalQuestion
@ CompanyControl
used in multiplayer to create a new companies etc.
@ AlterGroup
alter a group
@ EngineControl
control availability of the engine for companies
@ BuildIndustry
build a new industry
@ BuildCanal
build a canal
@ DeleteTown
delete a town
@ SetStoryPageDate
update date of a story page
@ FoundTown
found a town
@ BuildTunnel
build a tunnel
@ SetCompanyColour
set the colour of the company
@ BuildRoadWaypoint
build a road waypoint
@ IncreaseLoan
increase the loan from the bank
@ BuildBridge
build a bridge
@ SetVehicleVisibility
hide or unhide a vehicle in the build vehicle and autoreplace GUIs
@ AutoreplaceVehicle
replace/renew a vehicle while it is in a depot
@ BuildObjectArea
build an area of objects
@ CreateCustomNewsItem
create a custom news message
@ CreateLeagueTable
create a new league table
@ AddSharedVehiclesToGroup
add all other shared vehicles to a group which are missing
@ PlaceHouse
place a house
@ RenameCompany
change the company name
@ SetGoalText
update goal text of a goal
@ BuildShipDepot
build a ship depot
@ BuildVehicle
build a vehicle
@ UpdateStoryPageElement
update a story page element
@ BuyCompany
buy a company which is bankrupt
@ BuildDock
build a dock
@ CloneVehicle
clone a vehicle
@ BuildRailStation
build a rail station
@ BuildRailDepot
build a train depot
@ TownSetText
set the custom text of a town
@ RemoveFromRailStation
remove a (rectangle of) tiles from a rail station
@ SetGoalProgress
update goal progress text of a goal
@ MassStartStop
start/stop all vehicles (in a depot)
@ CreateLeagueTableElement
create a new element in a league table
@ DepotMassSell
sell all vehicles which are in a given depot
@ RenameEngine
rename a engine (in the engine list)
@ IndustrySetExclusivity
change industry exclusive consumer/supplier
@ OpenCloseAirport
open/close an airport to incoming aircraft
@ StoryPageButton
selection via story page button
@ TerraformLand
terraform a tile
@ MoveRailVehicle
move a rail vehicle (in the depot)
@ BuildRail
build a single rail track
@ RemoveLeagueTableElement
remove a league table element
@ BuildBuoy
build a buoy
@ RemoveFromRoadWaypoint
remove a (rectangle of) tiles from a road waypoint
@ RenamePresident
change the president name
@ RemoveAllVehiclesGroup
remove all vehicles from a group
@ ChangeBankBalance
change bank balance to charge costs or give money from a GS
@ TurnRoadVehicle
turn a road vehicle around
@ SetVehicleOnTime
set the vehicle on time feature (timetable)
@ BuildRailLong
build a rail track
@ RemoveStoryPage
remove a story page
@ SetCompanyMaxLoan
sets the max loan for the company
@ BuildRoad
build a "half" road
@ TownRating
set rating of a company in a town
@ RemoveSignal
remove a signal
@ MoveWaypointNAme
move a waypoint name
@ RemoveSignalLong
remove signals along a track (by dragging)
@ SetGoalCompleted
update goal completed status of a goal
@ RemoveRail
remove a single rail track
@ BuildSignalLong
add signals along a track (by dragging)
@ LevelLand
level land
@ RemoveRailLong
remove a rail track
@ CreateStoryPageElement
create a new story page element
@ CreateGroup
create a new group
@ SetAutoreplace
set an autoreplace entry
@ CreateStoryPage
create a new story page
@ RenameTown
rename a town
@ RenameVehicle
rename a whole vehicle
@ DeleteGroup
delete a group
@ RemoveFromRailWaypoint
remove a (rectangle of) tiles from a rail waypoint
@ BuildLock
build a lock
@ GiveMoney
give money to another company
@ ModifyOrder
modify an order (like set full-load)
@ ChangeCompanySetting
change a company setting
@ RemoveStoryPageElement
remove a story page element
@ BuildRoadLong
build a complete road (not a "half" one)
@ LandscapeClear
demolish a tile
@ BuildRoadStop
build a road stop
@ RenameWaypoint
rename a waypoint
@ SkipToOrder
skip an order to the next of specific one
@ CompanyAllowListControl
Used in multiplayer to add/remove a client's public key to/from the company's allow list.
Types related to companies.
A type is considered 'convertible through base()' when it has a 'base()' function that returns someth...
Types related to the economy.
ExpensesType
Types of expenses.
@ INVALID_EXPENSES
Invalid expense type.
static void SetGroupFlag(Group *g, GroupFlag flag, bool set, bool children)
Set group flag for a group and its sub-groups.
static void AddVehicleToGroup(Vehicle *v, GroupID new_g)
Do add a vehicle to a group.
ClientID
'Unique' identifier to be given to clients
void BuildObject(ObjectType type, TileIndex tile, CompanyID owner=OWNER_NONE, struct Town *town=nullptr, uint8_t view=0)
Actually build the object.
void InsertOrder(Vehicle *v, Order &&new_o, VehicleOrderID sel_ord)
Insert a new order but skip the validation.
void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord)
Delete an order but skip the parameter validation.
void MoveSign(SignID index, TileIndex tile)
Actually move the sign.
static bool RenameSign(SignID index, std::string_view text, Colours text_colour)
Actually rename the sign.
static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlags flags, int replacement_spec_index=-1)
Remove a bus station/truck stop.
Types related to strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames).
Info about each of the cheats.
Definition cheat_type.h:16
Defines the traits of a command.
Dynamic data of a loaded NewGRF.
Definition newgrf.h:117
void CreateSubsidy(CargoType cargo_type, Source src, Source dst)
Creates a subsidy with the given parameters.
Definition subsidy.cpp:173
Types related to tiles.
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 void ChangeTimetable(Vehicle *v, VehicleOrderID order_number, uint16_t val, ModifyTimetableFlags mtf, bool timetabled)
Change/update a particular timetable entry.
TownAction
Town actions of a company.
Definition town.h:248
static std::tuple< CommandCost, uint, uint16_t, CargoArray > RefitVehicle(Vehicle *v, bool only_this, uint8_t num_vehicles, CargoType new_cargo_type, uint8_t new_subtype, DoCommandFlags flags, bool auto_refit)
Refits a vehicle (chain).
void StartStopVehicle(const Vehicle *v, bool texteffect)
Executes Commands::StartStopVehicle for given vehicle.
void ReverseTrainDirection(Train *v)
Turn a train around.