OpenTTD Source 20261112-master-gbcbec5e63f
terraform_cmd.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 "command_func.h"
12#include "tilearea_type.h"
13#include "tunnel_map.h"
14#include "bridge_map.h"
15#include "viewport_func.h"
16#include "genworld.h"
17#include "object_base.h"
18#include "company_base.h"
19#include "company_func.h"
20#include "core/backup_type.hpp"
21#include "core/random_func.hpp"
22#include "terraform_cmd.h"
23#include "tile_cmd.h"
24#include "landscape_cmd.h"
25
26#include "table/strings.h"
27
28#include "safeguards.h"
29
31typedef std::set<TileIndex> TileIndexSet;
33typedef std::map<TileIndex, int> TileIndexToHeightMap;
34
40
49{
50 TileIndexToHeightMap::const_iterator it = ts->tile_to_new_height.find(tile);
51 return it != ts->tile_to_new_height.end() ? it->second : TileHeight(tile);
52}
53
61static void TerraformSetHeightOfTile(TerraformerState *ts, TileIndex tile, int height)
62{
63 ts->tile_to_new_height[tile] = height;
64}
65
74{
75 ts->dirty_tiles.insert(tile);
76}
77
86{
87 /* Make sure all tiles passed to TerraformAddDirtyTile are within [0, Map::Size()] */
88 if (TileY(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY( 0, -1));
89 if (TileY(tile) >= 1 && TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, -1));
90 if (TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, 0));
91 TerraformAddDirtyTile(ts, tile);
92}
93
102static std::tuple<CommandCost, TileIndex> TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height)
103{
104 assert(tile < Map::Size());
105
106 /* Check range of destination height */
107 if (height < 0) return { CommandCost(STR_ERROR_ALREADY_AT_SEA_LEVEL), INVALID_TILE };
108 if (height > _settings_game.construction.map_height_limit) return { CommandCost(STR_ERROR_TOO_HIGH), INVALID_TILE };
109
110 /*
111 * Check if the terraforming has any effect.
112 * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
113 * In this case the terraforming should fail. (Don't know why.)
114 */
115 if (height == TerraformGetHeightOfTile(ts, tile)) return { CMD_ERROR, INVALID_TILE };
116
117 /* Check "too close to edge of map". Only possible when freeform-edges is off. */
118 uint x = TileX(tile);
119 uint y = TileY(tile);
120 if (!_settings_game.construction.freeform_edges && ((x <= 1) || (y <= 1) || (x >= Map::MaxX() - 1) || (y >= Map::MaxY() - 1))) {
121 /*
122 * Determine a sensible error tile
123 */
124 if (x == 1) x = 0;
125 if (y == 1) y = 0;
126 return { CommandCost(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP), TileXY(x, y) };
127 }
128
129 /* Mark incident tiles that are involved in the terraforming. */
131
132 /* Store the height modification */
133 TerraformSetHeightOfTile(ts, tile, height);
134
136
137 /* Increment cost */
138 total_cost.AddCost(_price[Price::Terraform]);
139
140 /* Recurse to neighboured corners if height difference is larger than 1 */
142 TileIndex neighbour_tile = AddTileIndexDiffCWrap(tile, TileIndexDiffCByDiagDir(dir));
143
144 /* Not using IsValidTile as we want to also change TileType::Void tiles, which IsValidTile excludes. */
145 if (neighbour_tile == INVALID_TILE) continue;
146
147 /* Get TileHeight of neighboured tile as of current terraform progress */
148 int r = TerraformGetHeightOfTile(ts, neighbour_tile);
149 int height_diff = height - r;
150
151 /* Is the height difference to the neighboured corner greater than 1? */
152 if (abs(height_diff) > 1) {
153 /* Terraform the neighboured corner. The resulting height difference should be 1. */
154 height_diff += (height_diff < 0 ? 1 : -1);
155 auto [cost, err_tile] = TerraformTileHeight(ts, neighbour_tile, r + height_diff);
156 if (cost.Failed()) return { cost, err_tile };
157 total_cost.AddCost(cost.GetCost());
158 }
159 }
160
161 return { total_cost, INVALID_TILE };
162}
163
172std::tuple<CommandCost, Money, TileIndex> CmdTerraformLand(DoCommandFlags flags, TileIndex tile, Slope slope, bool dir_up)
173{
175 int direction = (dir_up ? 1 : -1);
177
178 /* Compute the costs and the terraforming result in a model of the landscape */
179 if ((slope & SLOPE_W) != 0 && tile + TileDiffXY(1, 0) < Map::Size()) {
180 TileIndex t = tile + TileDiffXY(1, 0);
181 auto [cost, err_tile] = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
182 if (cost.Failed()) return { cost, 0, err_tile };
183 total_cost.AddCost(cost.GetCost());
184 }
185
186 if ((slope & SLOPE_S) != 0 && tile + TileDiffXY(1, 1) < Map::Size()) {
187 TileIndex t = tile + TileDiffXY(1, 1);
188 auto [cost, err_tile] = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
189 if (cost.Failed()) return { cost, 0, err_tile };
190 total_cost.AddCost(cost.GetCost());
191 }
192
193 if ((slope & SLOPE_E) != 0 && tile + TileDiffXY(0, 1) < Map::Size()) {
194 TileIndex t = tile + TileDiffXY(0, 1);
195 auto [cost, err_tile] = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
196 if (cost.Failed()) return { cost, 0, err_tile };
197 total_cost.AddCost(cost.GetCost());
198 }
199
200 if ((slope & SLOPE_N) != 0) {
201 TileIndex t = tile + TileDiffXY(0, 0);
202 auto [cost, err_tile] = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
203 if (cost.Failed()) return { cost, 0, err_tile };
204 total_cost.AddCost(cost.GetCost());
205 }
206
207 /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface
208 * Pass == 0: Collect tileareas which are caused to be auto-cleared.
209 * Pass == 1: Collect the actual cost. */
210 for (int pass = 0; pass < 2; pass++) {
211 for (const auto &t : ts.dirty_tiles) {
212 assert(t < Map::Size());
213 /* TileType::Void tiles can be terraformed but as tunnels and bridges
214 * cannot go under / over these tiles they don't need checking. */
215 if (IsTileType(t, TileType::Void)) continue;
216
217 /* Find new heights of tile corners */
218 int z_N = TerraformGetHeightOfTile(&ts, t + TileDiffXY(0, 0));
219 int z_W = TerraformGetHeightOfTile(&ts, t + TileDiffXY(1, 0));
220 int z_S = TerraformGetHeightOfTile(&ts, t + TileDiffXY(1, 1));
221 int z_E = TerraformGetHeightOfTile(&ts, t + TileDiffXY(0, 1));
222
223 /* Find min and max height of tile */
224 int z_min = std::min({z_N, z_W, z_S, z_E});
225 int z_max = std::max({z_N, z_W, z_S, z_E});
226
227 /* Compute tile slope */
228 Slope tileh = (z_max > z_min + 1 ? SLOPE_STEEP : SLOPE_FLAT);
229 if (z_W > z_min) tileh |= SLOPE_W;
230 if (z_S > z_min) tileh |= SLOPE_S;
231 if (z_E > z_min) tileh |= SLOPE_E;
232 if (z_N > z_min) tileh |= SLOPE_N;
233
234 if (pass == 0) {
235 /* Check if bridge would take damage */
236 if (IsBridgeAbove(t)) {
237 int bridge_height = GetBridgeHeight(GetSouthernBridgeEnd(t));
238
239 /* Check if bridge would take damage. */
240 if (direction == 1 && bridge_height <= z_max) {
241 return { CommandCost(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST), 0, t }; // highlight the tile under the bridge
242 }
243
244 /* Is the bridge above not too high afterwards? */
245 if (direction == -1 && bridge_height > (z_min + _settings_game.construction.max_bridge_height)) {
246 return { CommandCost(STR_ERROR_BRIDGE_TOO_HIGH_AFTER_LOWER_LAND), 0, t };
247 }
248 }
249 /* Check if tunnel would take damage */
250 if (direction == -1 && IsTunnelInWay(t, z_min)) {
251 return { CommandCost(STR_ERROR_EXCAVATION_WOULD_DAMAGE), 0, t }; // highlight the tile above the tunnel
252 }
253 }
254
255 /* Is the tile already cleared? */
256 const ClearedObjectArea *coa = FindClearedObject(t);
257 bool indirectly_cleared = coa != nullptr && coa->first_tile != t;
258
259 /* Check tiletype-specific things, and add extra-cost */
260 Backup<bool> old_generating_world(_generating_world);
261 if (_game_mode == GameMode::Editor) old_generating_world.Change(true); // used to create green terraformed land
263
264 /* If the tile is being lowered, maybe make rocks to simulate excavation/blasting. Higher elevations are more likely to get rocks.
265 * Only do this if executing the command, as a test run of RandomRange will cause a desync. */
266 if (flags.Test(DoCommandFlag::Execute)) {
267 bool make_rocks = RandomRange(_settings_game.construction.map_height_limit) <= static_cast<uint32_t>(z_max);
268 if (!dir_up && make_rocks) tile_flags = tile_flags | DoCommandFlag::ClearToRocks;
269 }
270
271 if (pass == 0) {
272 tile_flags.Reset(DoCommandFlag::Execute);
274 }
275 CommandCost cost;
276 if (indirectly_cleared) {
277 cost = Command<Commands::LandscapeClear>::Do(tile_flags, t);
278 } else {
279 cost = _tile_type_procs[GetTileType(t)]->terraform_tile_proc(t, tile_flags, z_min, tileh);
280 }
281 old_generating_world.Restore();
282 if (cost.Failed()) {
283 return { cost, 0, t };
284 }
285 if (pass == 1) total_cost.AddCost(cost.GetCost());
286 }
287 }
288
290 if (c != nullptr && GB(c->terraform_limit, 16, 16) < ts.tile_to_new_height.size()) {
291 return { CommandCost(STR_ERROR_TERRAFORM_LIMIT_REACHED), 0, INVALID_TILE };
292 }
293
294 if (flags.Test(DoCommandFlag::Execute)) {
295 /* Mark affected areas dirty. */
296 for (const auto &t : ts.dirty_tiles) {
298 TileIndexToHeightMap::const_iterator new_height = ts.tile_to_new_height.find(t);
299 if (new_height == ts.tile_to_new_height.end()) continue;
300 MarkTileDirtyByTile(t, 0, new_height->second);
301 }
302
303 /* change the height */
304 for (const auto &it : ts.tile_to_new_height) {
305 TileIndex t = it.first;
306 int height = it.second;
307
308 SetTileHeight(t, (uint)height);
309 }
310
311 if (c != nullptr) c->terraform_limit -= (uint32_t)ts.tile_to_new_height.size() << 16;
312 }
313 return { total_cost, 0, total_cost.Succeeded() ? tile : INVALID_TILE };
314}
315
316
326std::tuple<CommandCost, Money, TileIndex> CmdLevelLand(DoCommandFlags flags, TileIndex tile, TileIndex start_tile, bool diagonal, LevelMode lm)
327{
328 if (start_tile >= Map::Size()) return { CMD_ERROR, 0, INVALID_TILE };
329
330 /* remember level height */
331 uint oldh = TileHeight(start_tile);
332
333 /* compute new height */
334 uint h = oldh;
335 switch (lm) {
336 case LevelMode::Level: break;
337 case LevelMode::Raise: h++; break;
338 case LevelMode::Lower: h--; break;
339 default: return { CMD_ERROR, 0, INVALID_TILE };
340 }
341
342 /* Check range of destination height */
343 if (h > _settings_game.construction.map_height_limit) return { CommandCost(oldh == 0 ? STR_ERROR_ALREADY_AT_SEA_LEVEL : STR_ERROR_TOO_HIGH), 0, INVALID_TILE };
344
345 Money money = GetAvailableMoneyForCommand();
347 CommandCost last_error(lm == LevelMode::Level ? STR_ERROR_ALREADY_LEVELLED : INVALID_STRING_ID);
348 bool had_success = false;
349
351 int limit = (c == nullptr ? INT32_MAX : GB(c->terraform_limit, 16, 16));
352 if (limit == 0) return { CommandCost(STR_ERROR_TERRAFORM_LIMIT_REACHED), 0, INVALID_TILE };
353
354 TileIndex error_tile = INVALID_TILE;
355 for (TileIndex t : CreateOrthoDiagonalArea(tile, start_tile, diagonal)) {
356 uint curh = TileHeight(t);
357 while (curh != h) {
358 CommandCost ret;
359 std::tie(ret, std::ignore, error_tile) = Command<Commands::TerraformLand>::Do(DoCommandFlags{flags}.Reset(DoCommandFlag::Execute), t, SLOPE_N, curh <= h);
360 if (ret.Failed()) {
361 last_error = std::move(ret);
362
363 /* Did we reach the limit? */
364 if (last_error.GetErrorMessage() == STR_ERROR_TERRAFORM_LIMIT_REACHED) limit = 0;
365 break;
366 }
367
368 if (flags.Test(DoCommandFlag::Execute)) {
369 money -= ret.GetCost();
370 if (money < 0) {
371 return { cost, ret.GetCost(), error_tile };
372 }
373 Command<Commands::TerraformLand>::Do(flags, t, SLOPE_N, curh <= h);
374 } else {
375 /* When we're at the terraform limit we better bail (unneeded) testing as well.
376 * This will probably cause the terraforming cost to be underestimated, but only
377 * when it's near the terraforming limit. Even then, the estimation is
378 * completely off due to it basically counting terraforming double, so it being
379 * cut off earlier might even give a better estimate in some cases. */
380 if (--limit <= 0) {
381 had_success = true;
382 break;
383 }
384 }
385
386 cost.AddCost(ret.GetCost());
387 curh += (curh > h) ? -1 : 1;
388 had_success = true;
389 }
390
391 if (limit <= 0) break;
392 }
393
394 CommandCost cc_ret = had_success ? cost : last_error;
395 return { cc_ret, 0, cc_ret.Succeeded() ? tile : error_tile };
396}
Class for backupping variables and making sure they are restored later.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
TileIndex GetSouthernBridgeEnd(TileIndex t)
Finds the southern end of a bridge starting at a middle tile.
int GetBridgeHeight(TileIndex t)
Get the height ('z') of a bridge.
Map accessor functions for bridges.
bool IsBridgeAbove(Tile t)
checks if a bridge is set above the ground of this tile
Definition bridge_map.h:45
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
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.
bool Failed() const
Did this command fail?
StringID GetErrorMessage() const
Returns the error message of a command.
Iterate a range of enum values.
Functions related to commands.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
@ Auto
don't allow building on structures
@ NoModifyTownRating
do not change town rating
@ ClearToRocks
when clearing land, make rocks instead of bare dirt/grass
@ Execute
execute the given command
@ ForceClearTile
do not only remove the object on the tile, but also clear any water left on it
EnumBitSet< DoCommandFlag, uint16_t > DoCommandFlags
Bitset of DoCommandFlag elements.
Definition of stuff that is very close to a company, like the company struct itself.
Money GetAvailableMoneyForCommand()
This functions returns the money which can be used to execute a command.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
DiagDirection
Enumeration for diagonal directions.
@ End
Used for iterations.
Prices _price
Prices and also the fractional part.
Definition economy.cpp:109
@ Construction
Construction costs.
@ Terraform
Price for terraforming land, e.g. rising, lowering and flattening.
bool _generating_world
Whether we are generating the map or not.
Definition genworld.cpp:70
Functions related to world/map generation.
static void TerraformAddDirtyTile(TerraformerState *ts, TileIndex tile)
Adds a tile to the "tile_table" in a TerraformerState.
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
static void TerraformAddDirtyTileAround(TerraformerState *ts, TileIndex tile)
Adds all tiles that incident with the north corner of a specific tile to the "tile_table" in a Terraf...
const EnumIndexArray< const TileTypeProcs *, TileType, TileType::MaxSize > _tile_type_procs
Tile callback functions for each type of tile.
Definition landscape.cpp:71
Command definitions related to landscape (slopes etc.).
TileIndex AddTileIndexDiffCWrap(TileIndex tile, TileIndexDiffC diff)
Add a TileIndexDiffC to a TileIndex and returns the new one.
Definition map_func.h:519
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:392
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:376
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
TileIndexDiffC TileIndexDiffCByDiagDir(DiagDirection dir)
Returns the TileIndexDiffC offset from a DiagDirection.
Definition map_func.h:487
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
LevelMode
Argument for CmdLevelLand describing what to do.
Definition map_type.h:43
@ Raise
Raise the land.
Definition map_type.h:46
@ Level
Level the land.
Definition map_type.h:44
@ Lower
Lower the land.
Definition map_type.h:45
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
Base for all objects.
ClearedObjectArea * FindClearedObject(TileIndex tile)
Find the entry in _cleared_object_areas which occupies a certain tile.
@ Editor
In the scenario editor.
Definition openttd.h:21
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
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
Slope
Enumeration for the slope-type.
Definition slope_type.h:53
@ SLOPE_W
the west corner of the tile is raised
Definition slope_type.h:55
@ SLOPE_E
the east corner of the tile is raised
Definition slope_type.h:57
@ SLOPE_S
the south corner of the tile is raised
Definition slope_type.h:56
@ SLOPE_N
the north corner of the tile is raised
Definition slope_type.h:58
@ SLOPE_FLAT
a flat tile
Definition slope_type.h:54
@ SLOPE_STEEP
indicates the slope is steep
Definition slope_type.h:59
Definition of base types and functions in a cross-platform compatible way.
static constexpr 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.
void Change(const U &new_value)
Change the value of the variable.
void Restore()
Restore the variable.
Keeps track of removed objects during execution/testruns of commands.
Definition object_base.h:84
TileIndex first_tile
The first tile being cleared, which then causes the whole object to be cleared.
Definition object_base.h:85
uint32_t terraform_limit
Amount of tileheights we can (still) terraform (times 65536).
static uint MaxY()
Gets the maximum Y coordinate within the map, including TileType::Void.
Definition map_func.h:298
static uint MaxX()
Gets the maximum X coordinate within the map, including TileType::Void.
Definition map_func.h:289
static uint Size()
Get the size of the map.
Definition map_func.h:280
static Company * GetIfValid(auto index)
State of the terraforming.
TileIndexSet dirty_tiles
The tiles that need to be redrawn.
TileIndexToHeightMap tile_to_new_height
The tiles for which the height has changed.
static std::tuple< CommandCost, TileIndex > TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height)
Terraform the north corner of a tile to a specific height.
static int TerraformGetHeightOfTile(const TerraformerState *ts, TileIndex tile)
Gets the TileHeight (height of north corner) of a tile as of current terraforming progress.
std::tuple< CommandCost, Money, TileIndex > CmdLevelLand(DoCommandFlags flags, TileIndex tile, TileIndex start_tile, bool diagonal, LevelMode lm)
Levels a selected (rectangle) area of land.
std::set< TileIndex > TileIndexSet
Set of tiles.
std::tuple< CommandCost, Money, TileIndex > CmdTerraformLand(DoCommandFlags flags, TileIndex tile, Slope slope, bool dir_up)
Terraform land.
static void TerraformSetHeightOfTile(TerraformerState *ts, TileIndex tile, int height)
Stores the TileHeight (height of north corner) of a tile in a TerraformerState.
std::map< TileIndex, int > TileIndexToHeightMap
Mapping of tiles to their height.
Command definitions related to terraforming.
Generic 'commands' that can be performed on all tiles.
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
static uint TileHeight(Tile tile)
Returns the height of a tile.
Definition tile_map.h:29
void SetTileHeight(Tile tile, uint height)
Sets the height of a tile.
Definition tile_map.h:57
static TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition tile_map.h:96
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
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
@ Void
Invisible tiles at the SW and SE border.
Definition tile_type.h:56
OrthoDiagonalTileArea CreateOrthoDiagonalArea(TileIndex corner1, TileIndex corner2, bool diagonal)
Create an Orthogonal/Diagonal tile area wrapper.
Definition tilearea.cpp:23
Type for storing the 'area' of something uses on the map.
bool IsTunnelInWay(TileIndex tile, int z)
Is there a tunnel in the way in any direction?
Map accessors for tunnels.
Functions related to (drawing on) viewports.