OpenTTD Source 20260218-master-g2123fca5ea
command_func.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_FUNC_H
11#define COMMAND_FUNC_H
12
13#include "command_type.h"
15#include "company_type.h"
16#include "company_func.h"
17#include "core/backup_type.hpp"
19#include "tile_map.h"
20
29
30void NetworkSendCommand(Commands cmd, StringID err_message, CommandCallback *callback, CompanyID company, const CommandDataBuffer &cmd_data);
32
33bool IsValidCommand(Commands cmd);
34CommandFlags GetCommandFlags(Commands cmd);
35std::string_view GetCommandName(Commands cmd);
37
38template <Commands Tcmd>
39constexpr CommandFlags GetCommandFlags()
40{
42}
43
49static constexpr inline DoCommandFlags CommandFlagsToDCFlags(CommandFlags cmd_flags)
50{
51 DoCommandFlags flags = {};
53 if (cmd_flags.Test(CommandFlag::Auto)) flags.Set(DoCommandFlag::Auto);
55 return flags;
56}
57
59struct RecursiveCommandCounter {
60 RecursiveCommandCounter() noexcept { _counter++; }
61 ~RecursiveCommandCounter() noexcept { _counter--; }
62
67 bool IsTopLevel() const { return _counter == 1; }
68private:
69 static int _counter;
70};
71
72#if defined(__GNUC__) && !defined(__clang__)
73/*
74 * We cast specialized function pointers to a generic one, but don't use the
75 * converted value to call the function, which is safe, except that GCC
76 * helpfully thinks it is not.
77 *
78 * "Any pointer to function can be converted to a pointer to a different function type.
79 * Calling the function through a pointer to a different function type is undefined,
80 * but converting such pointer back to pointer to the original function type yields
81 * the pointer to the original function." */
82# pragma GCC diagnostic push
83# pragma GCC diagnostic ignored "-Wcast-function-type"
84# define SILENCE_GCC_FUNCTION_POINTER_CAST
85#endif
86
87template <Commands TCmd, typename T, bool THasTile> struct CommandHelper;
88
90protected:
91 static void InternalDoBefore(bool top_level, bool test);
92 static void InternalDoAfter(CommandCost &res, DoCommandFlags flags, bool top_level, bool test);
93 static std::tuple<bool, bool, bool> InternalPostBefore(Commands cmd, CommandFlags flags, TileIndex tile, StringID err_message, bool network_command);
94 static void InternalPostResult(CommandCost &res, TileIndex tile, bool estimate_only, bool only_sending, StringID err_message, bool my_cmd);
95 static bool InternalExecutePrepTest(CommandFlags cmd_flags, Backup<CompanyID> &cur_company);
96 static std::tuple<bool, bool, bool> InternalExecuteValidateTestAndPrepExec(CommandCost &res, CommandFlags cmd_flags, bool estimate_only, bool network_command, Backup<CompanyID> &cur_company);
97 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);
98 static void LogCommandExecution(Commands cmd, StringID err_message, const CommandDataBuffer &args, bool failed);
99};
100
108template <Commands Tcmd, typename Tret, typename... Targs>
109struct CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), true> : protected CommandHelperBase {
110private:
116 static inline CommandCost &ExtractCommandCost(Tret &ret)
117 {
118 if constexpr (std::is_same_v<Tret, CommandCost>) {
119 return ret;
120 } else {
121 return std::get<0>(ret);
122 }
123 }
124
130 static inline Tret MakeResult(const CommandCost &cost)
131 {
132 Tret ret{};
133 ExtractCommandCost(ret) = cost;
134 return ret;
135 }
136
137public:
150 static Tret Do(DoCommandFlags flags, Targs... args)
151 {
152 if constexpr (std::is_same_v<TileIndex, std::tuple_element_t<0, std::tuple<Targs...>>>) {
153 /* Do not even think about executing out-of-bounds tile-commands. */
154 TileIndex tile = std::get<0>(std::make_tuple(args...));
155 if (tile != 0 && (tile >= Map::Size() || (!IsValidTile(tile) && !flags.Test(DoCommandFlag::AllTiles)))) return MakeResult(CMD_ERROR);
156 }
157
158 RecursiveCommandCounter counter{};
159
160 /* Only execute the test call if it's toplevel, or we're not execing. */
161 if (counter.IsTopLevel() || !flags.Test(DoCommandFlag::Execute)) {
162 InternalDoBefore(counter.IsTopLevel(), true);
163 Tret res = CommandTraits<Tcmd>::proc(DoCommandFlags{flags}.Reset(DoCommandFlag::Execute), args...);
164 InternalDoAfter(ExtractCommandCost(res), flags, counter.IsTopLevel(), true); // Can modify res.
165
166 if (ExtractCommandCost(res).Failed() || !flags.Test(DoCommandFlag::Execute)) return res;
167 }
168
169 /* Execute the command here. All cost-relevant functions set the expenses type
170 * themselves to the cost object at some point. */
171 InternalDoBefore(counter.IsTopLevel(), false);
172 Tret res = CommandTraits<Tcmd>::proc(flags, args...);
173 InternalDoAfter(ExtractCommandCost(res), flags, counter.IsTopLevel(), false);
174
175 return res;
176 }
177
184 static inline bool Post(StringID err_message, Targs... args) { return Post<CommandCallback>(err_message, nullptr, std::forward<Targs>(args)...); }
185
192 template <typename Tcallback>
193 static inline bool Post(Tcallback *callback, Targs... args) { return Post((StringID)0, callback, std::forward<Targs>(args)...); }
194
200 static inline bool Post(Targs... args) { return Post<CommandCallback>((StringID)0, nullptr, std::forward<Targs>(args)...); }
201
212 template <typename Tcallback>
213 static bool Post(StringID err_message, Tcallback *callback, Targs... args)
214 {
215 assert(::IsNetworkRegisteredCallback(reinterpret_cast<CommandCallback *>(reinterpret_cast<void(*)()>(callback))));
216 return InternalPost(err_message, callback, true, false, std::forward_as_tuple(args...));
217 }
218
227 template <typename Tcallback>
228 static bool PostFromNet(StringID err_message, Tcallback *callback, bool my_cmd, std::tuple<Targs...> args)
229 {
230 return InternalPost(err_message, callback, my_cmd, true, std::move(args));
231 }
232
239 static void SendNet(StringID err_message, CompanyID company, Targs... args)
240 {
241 auto args_tuple = std::forward_as_tuple(args...);
242
243 ::NetworkSendCommand(Tcmd, err_message, nullptr, company, EndianBufferWriter<CommandDataBuffer>::FromValue(args_tuple));
244 }
245
256 template <typename Tcallback>
257 static Tret Unsafe(StringID err_message, Tcallback *callback, bool my_cmd, bool estimate_only, TileIndex location, std::tuple<Targs...> args)
258 {
259 return Execute(err_message, reinterpret_cast<CommandCallback *>(reinterpret_cast<void(*)()>(callback)), my_cmd, estimate_only, false, location, std::move(args));
260 }
261
262protected:
267 template <class T>
268 static inline void SetClientIdHelper([[maybe_unused]] T &data)
269 {
270 if constexpr (std::is_same_v<ClientID, T>) {
271 if (data == INVALID_CLIENT_ID) data = CLIENT_ID_SERVER;
272 }
273 }
274
279 template <class Ttuple, size_t... Tindices>
280 static inline void SetClientIds(Ttuple &values, std::index_sequence<Tindices...>)
281 {
282 ((SetClientIdHelper(std::get<Tindices>(values))), ...);
283 }
284
290 template <template <typename...> typename Tt, typename T1, typename... Ts>
291 static inline Tt<Ts...> RemoveFirstTupleElement(const Tt<T1, Ts...> &tuple)
292 {
293 return std::apply([](auto &&, const auto&... args) { return std::tie(args...); }, tuple);
294 }
295
296 template <typename Tcallback>
297 static bool InternalPost(StringID err_message, Tcallback *callback, bool my_cmd, bool network_command, std::tuple<Targs...> args)
298 {
299 /* Where to show the message? */
300 TileIndex tile{};
301 if constexpr (std::is_same_v<TileIndex, std::tuple_element_t<0, decltype(args)>>) {
302 tile = std::get<0>(args);
303 }
304
305 return InternalPost(err_message, callback, my_cmd, network_command, tile, std::move(args));
306 }
307
308 template <typename Tcallback>
309 static bool InternalPost(StringID err_message, Tcallback *callback, bool my_cmd, bool network_command, TileIndex tile, std::tuple<Targs...> args)
310 {
311 /* Do not even think about executing out-of-bounds tile-commands. */
312 if (tile != 0 && (tile >= Map::Size() || (!IsValidTile(tile) && !GetCommandFlags<Tcmd>().Test(CommandFlag::AllTiles)))) return false;
313
314 auto [err, estimate_only, only_sending] = InternalPostBefore(Tcmd, GetCommandFlags<Tcmd>(), tile, err_message, network_command);
315 if (err) return false;
316
317 /* Only set client IDs when the command does not come from the network. */
318 if (!network_command && GetCommandFlags<Tcmd>().Test(CommandFlag::ClientID)) SetClientIds(args, std::index_sequence_for<Targs...>{});
319
320 Tret res = Execute(err_message, reinterpret_cast<CommandCallback *>(reinterpret_cast<void(*)()>(callback)), my_cmd, estimate_only, network_command, tile, args);
321 InternalPostResult(ExtractCommandCost(res), tile, estimate_only, only_sending, err_message, my_cmd);
322
323 if (!estimate_only && !only_sending && callback != nullptr) {
324 if constexpr (std::is_same_v<Tcallback, CommandCallback>) {
325 /* Callback that doesn't need any command arguments. */
326 callback(Tcmd, ExtractCommandCost(res), tile);
327 } else if constexpr (std::is_same_v<Tcallback, CommandCallbackData>) {
328 /* Generic callback that takes packed arguments as a buffer. */
329 if constexpr (std::is_same_v<Tret, CommandCost>) {
330 callback(Tcmd, ExtractCommandCost(res), EndianBufferWriter<CommandDataBuffer>::FromValue(args), {});
331 } else {
332 callback(Tcmd, ExtractCommandCost(res), EndianBufferWriter<CommandDataBuffer>::FromValue(args), EndianBufferWriter<CommandDataBuffer>::FromValue(RemoveFirstTupleElement(res)));
333 }
334 } else if constexpr (!std::is_same_v<Tret, CommandCost> && std::is_same_v<Tcallback *, typename CommandTraits<Tcmd>::RetCallbackProc>) {
335 std::apply(callback, std::tuple_cat(std::make_tuple(Tcmd), res));
336 } else {
337 /* Callback with arguments. We assume that the tile is only interesting if it actually is in the command arguments. */
338 if constexpr (std::is_same_v<Tret, CommandCost>) {
339 std::apply(callback, std::tuple_cat(std::make_tuple(Tcmd, res), args));
340 } else {
341 std::apply(callback, std::tuple_cat(std::make_tuple(Tcmd), res, args));
342 }
343 }
344 }
345
346 return ExtractCommandCost(res).Succeeded();
347 }
348
354 template <class T>
355 static inline bool ClientIdIsSet([[maybe_unused]] T &data)
356 {
357 if constexpr (std::is_same_v<ClientID, T>) {
358 return data != INVALID_CLIENT_ID;
359 } else {
360 return true;
361 }
362 }
363
369 template <class Ttuple, size_t... Tindices>
370 static inline bool AllClientIdsSet(Ttuple &values, std::index_sequence<Tindices...>)
371 {
372 return (ClientIdIsSet(std::get<Tindices>(values)) && ...);
373 }
374
375 template <class Ttuple>
376 static inline Money ExtractAdditionalMoney([[maybe_unused]] Ttuple &values)
377 {
378 if constexpr (std::is_same_v<std::tuple_element_t<1, Tret>, Money>) {
379 return std::get<1>(values);
380 } else {
381 return {};
382 }
383 }
384
385 static Tret Execute(StringID err_message, CommandCallback *callback, bool, bool estimate_only, bool network_command, TileIndex tile, std::tuple<Targs...> args)
386 {
387 /* Prevent recursion; it gives a mess over the network */
388 RecursiveCommandCounter counter{};
389 assert(counter.IsTopLevel());
390
391 /* Command flags are used internally */
392 constexpr CommandFlags cmd_flags = GetCommandFlags<Tcmd>();
393
394 if constexpr (cmd_flags.Test(CommandFlag::ClientID)) {
395 /* Make sure arguments are properly set to a ClientID also when processing external commands. */
396 assert(AllClientIdsSet(args, std::index_sequence_for<Targs...>{}));
397 }
398
400 if (!InternalExecutePrepTest(cmd_flags, cur_company)) {
401 cur_company.Trash();
402 return MakeResult(CMD_ERROR);
403 }
404
405 /* Test the command. */
406 DoCommandFlags flags = CommandFlagsToDCFlags(cmd_flags);
407 Tret res = std::apply(CommandTraits<Tcmd>::proc, std::tuple_cat(std::make_tuple(flags), args));
408
409 auto [exit_test, desync_log, send_net] = InternalExecuteValidateTestAndPrepExec(ExtractCommandCost(res), cmd_flags, estimate_only, network_command, cur_company);
410 if (exit_test) {
411 if (desync_log) LogCommandExecution(Tcmd, err_message, EndianBufferWriter<CommandDataBuffer>::FromValue(args), true);
412 cur_company.Restore();
413 return res;
414 }
415
416 /* If we are in network, and the command is not from the network
417 * send it to the command-queue and abort execution. */
418 if (send_net) {
419 ::NetworkSendCommand(Tcmd, err_message, callback, _current_company, EndianBufferWriter<CommandDataBuffer>::FromValue(args));
420 cur_company.Restore();
421
422 /* Don't return anything special here; no error, no costs.
423 * This way it's not handled by DoCommand and only the
424 * actual execution of the command causes messages. Also
425 * reset the storages as we've not executed the command. */
426 return {};
427 }
428
429 if (desync_log) LogCommandExecution(Tcmd, err_message, EndianBufferWriter<CommandDataBuffer>::FromValue(args), false);
430
431 /* Actually try and execute the command. */
432 Tret res2 = std::apply(CommandTraits<Tcmd>::proc, std::tuple_cat(std::make_tuple(flags | DoCommandFlag::Execute), args));
433
434 /* Convention: If the second result element is of type Money,
435 * this is the additional cash required for the command. */
436 Money additional_money{};
437 if constexpr (!std::is_same_v<Tret, CommandCost>) { // No short-circuiting for 'if constexpr'.
438 additional_money = ExtractAdditionalMoney(res2);
439 }
440
441 if constexpr (std::is_same_v<Tret, CommandCost>) {
442 return InternalExecuteProcessResult(Tcmd, cmd_flags, res, res2, additional_money, tile, cur_company);
443 } else {
444 std::get<0>(res2) = InternalExecuteProcessResult(Tcmd, cmd_flags, ExtractCommandCost(res), ExtractCommandCost(res2), additional_money, tile, cur_company);
445 return res2;
446 }
447 }
448};
449
457template <Commands Tcmd, typename Tret, typename... Targs>
458struct CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), false> : CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), true>
459{
460 /* Do not allow Post without explicit location. */
461 static inline bool Post(StringID err_message, Targs... args) = delete;
462 template <typename Tcallback>
463 static inline bool Post(Tcallback *callback, Targs... args) = delete;
464 static inline bool Post(Targs... args) = delete;
465 template <typename Tcallback>
466 static bool Post(StringID err_message, Tcallback *callback, Targs... args) = delete;
467
475 static inline bool Post(StringID err_message, TileIndex location, Targs... args) { return Post<CommandCallback>(err_message, nullptr, location, std::forward<Targs>(args)...); }
476
484 template <typename Tcallback>
485 static inline bool Post(Tcallback *callback, TileIndex location, Targs... args) { return Post((StringID)0, callback, location, std::forward<Targs>(args)...); }
486
493 static inline bool Post(TileIndex location, Targs... args) { return Post<CommandCallback>((StringID)0, nullptr, location, std::forward<Targs>(args)...); }
494
504 template <typename Tcallback>
505 static inline bool Post(StringID err_message, Tcallback *callback, TileIndex location, Targs... args)
506 {
507 return CommandHelper<Tcmd, Tret(*)(DoCommandFlags, Targs...), true>::InternalPost(err_message, callback, true, false, location, std::forward_as_tuple(args...));
508 }
509};
510
511#ifdef SILENCE_GCC_FUNCTION_POINTER_CAST
512# pragma GCC diagnostic pop
513#endif
514
515template <Commands Tcmd>
517
518#endif /* COMMAND_FUNC_H */
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 Timpl & Set()
Set all bits.
Common return value for all commands.
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:200
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:231
static void InternalDoBefore(bool top_level, bool test)
Prepare for calling a command proc.
Definition command.cpp:162
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:260
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:341
static bool InternalExecutePrepTest(CommandFlags cmd_flags, Backup< CompanyID > &cur_company)
Prepare for the test run of a command proc call.
Definition command.cpp:271
static void InternalDoAfter(CommandCost &res, DoCommandFlags flags, bool top_level, bool test)
Process result after calling a command proc.
Definition command.cpp:175
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:301
CommandFlags GetCommandFlags(Commands cmd)
Get the command flags associated with the given command.
Definition command.cpp:113
CommandFlags GetCommandFlags(Commands cmd)
Get the command flags associated with the given command.
Definition command.cpp:113
bool IsCommandAllowedWhilePaused(Commands cmd)
Returns whether the command is allowed while the game is paused.
Definition command.cpp:137
static constexpr DoCommandFlags CommandFlagsToDCFlags(CommandFlags cmd_flags)
Extracts the DC flags needed for DoCommand from the flags returned by GetCommandFlags.
bool IsNetworkRegisteredCallback(CommandCallback *callback)
Helper function to ensure that callbacks used when Posting commands are actually registered for the n...
std::string_view GetCommandName(Commands cmd)
Get the name of the given command.
Definition command.cpp:125
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
bool IsValidCommand(Commands cmd)
This function range-checks a Commands.
Definition command.cpp:103
void NetworkSendCommand(Commands cmd, StringID err_message, CommandCallback *callback, CompanyID company, const CommandDataBuffer &cmd_data)
Prepare a DoCommand to be send over the network.
Types related to commands.
void CommandCallback(Commands cmd, const CommandCost &result, TileIndex tile)
Define a callback function for the client, after the command is finished.
@ Auto
don't allow building on structures
@ NoWater
don't allow building on water
@ Execute
execute the given command
@ AllTiles
allow this command also on TileType::Void tiles
@ Auto
set the DoCommandFlag::Auto flag on this command
@ NoWater
set the DoCommandFlag::NoWater flag on this command
@ AllTiles
allow this command also on TileType::Void tiles
@ ClientID
set p2 with the ClientID of the sending client.
@ Location
the command has implicit location argument.
std::vector< uint8_t > CommandDataBuffer
Storage buffer for serialized command data.
Commands
List of commands.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
Types related to companies.
Endian-aware buffer.
static void SetClientIds(Ttuple &values, ClientID client_id, std::index_sequence< Tindices... >)
Set all invalid ClientIDs to the proper value.
static void SetClientIdHelper(T &data, ClientID client_id)
Helper to process a single ClientID argument.
Types used for networking.
@ INVALID_CLIENT_ID
Client is not part of anything.
@ CLIENT_ID_SERVER
Servers always have this ID.
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).
Class to backup a specific variable and restore it later.
static bool Post(TileIndex location, Targs... args)
Shortcut for Post when not using a callback or an error message.
static bool Post(StringID err_message, Tcallback *callback, TileIndex location, Targs... args)
Post variant that takes a TileIndex (for error window location and text effects) for commands that do...
static bool Post(StringID err_message, TileIndex location, Targs... args)
Shortcut for Post when not using a callback.
static bool Post(Tcallback *callback, TileIndex location, Targs... args)
Shortcut for Post when not using an error message.
static bool Post(StringID err_message, Tcallback *callback, Targs... args)
Top-level network safe command execution for the current company.
static Tret Do(DoCommandFlags flags, Targs... args)
This function executes a given command.
static bool ClientIdIsSet(T &data)
Helper to process a single ClientID argument.
static bool Post(StringID err_message, Targs... args)
Shortcut for the long Post when not using a callback.
static void SetClientIdHelper(T &data)
Helper to process a single ClientID argument.
static bool PostFromNet(StringID err_message, Tcallback *callback, bool my_cmd, std::tuple< Targs... > args)
Execute a command coming from the network.
static Tret Unsafe(StringID err_message, Tcallback *callback, bool my_cmd, bool estimate_only, TileIndex location, std::tuple< Targs... > args)
Top-level network safe command execution without safety checks.
static void SendNet(StringID err_message, CompanyID company, Targs... args)
Prepare a command to be send over the network.
static bool Post(Tcallback *callback, Targs... args)
Shortcut for the long Post when not using an error message.
static Tt< Ts... > RemoveFirstTupleElement(const Tt< T1, Ts... > &tuple)
Remove the first element of a tuple.
static Tret MakeResult(const CommandCost &cost)
Make a command proc result from a CommandCost.
static bool Post(Targs... args)
Shortcut for the long Post when not using a callback or an error message.
static bool AllClientIdsSet(Ttuple &values, std::index_sequence< Tindices... >)
Check if all ClientID arguments are set to valid values.
static CommandCost & ExtractCommandCost(Tret &ret)
Extract the CommandCost from a command proc result.
static void SetClientIds(Ttuple &values, std::index_sequence< Tindices... >)
Set all invalid ClientIDs to the proper value.
Defines the traits of a command.
static uint Size()
Get the size of the map.
Definition map_func.h:282
Helper class to keep track of command nesting level.
static int _counter
Number of instances of this class.
bool IsTopLevel() const
Are we in the top-level command execution?
Map writing/reading functions for tiles.
bool IsValidTile(Tile tile)
Checks if a tile is valid.
Definition tile_map.h:161
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