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/>.
8 /** @file terraform_cmd.cpp Commands related to terraforming. */
11 #include "command_func.h"
12 #include "tunnel_map.h"
13 #include "bridge_map.h"
14 #include "viewport_func.h"
16 #include "object_base.h"
17 #include "company_base.h"
18 #include "company_func.h"
20 #include "table/strings.h"
25 #include "safeguards.h"
28 typedef std::set
<TileIndex
> TileIndexSet
;
29 /** Mapping of tiles to their height. */
30 typedef std::map
<TileIndex
, int> TileIndexToHeightMap
;
32 /** State of the terraforming. */
33 struct TerraformerState
{
34 TileIndexSet dirty_tiles
; ///< The tiles that need to be redrawn.
35 TileIndexToHeightMap tile_to_new_height
; ///< The tiles for which the height has changed.
38 TileIndex _terraform_err_tile
; ///< first tile we couldn't terraform
41 * Gets the TileHeight (height of north corner) of a tile as of current terraforming progress.
43 * @param ts TerraformerState.
47 static int TerraformGetHeightOfTile(const TerraformerState
*ts
, TileIndex tile
)
49 TileIndexToHeightMap::const_iterator it
= ts
->tile_to_new_height
.find(tile
);
50 return it
!= ts
->tile_to_new_height
.end() ? it
->second
: TileHeight(tile
);
54 * Stores the TileHeight (height of north corner) of a tile in a TerraformerState.
56 * @param ts TerraformerState.
58 * @param height New TileHeight.
60 static void TerraformSetHeightOfTile(TerraformerState
*ts
, TileIndex tile
, int height
)
62 ts
->tile_to_new_height
[tile
] = height
;
66 * Adds a tile to the "tile_table" in a TerraformerState.
68 * @param ts TerraformerState.
72 static void TerraformAddDirtyTile(TerraformerState
*ts
, TileIndex tile
)
74 ts
->dirty_tiles
.insert(tile
);
78 * Adds all tiles that incident with the north corner of a specific tile to the "tile_table" in a TerraformerState.
80 * @param ts TerraformerState.
84 static void TerraformAddDirtyTileAround(TerraformerState
*ts
, TileIndex tile
)
86 /* Make sure all tiles passed to TerraformAddDirtyTile are within [0, MapSize()] */
87 if (TileY(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY( 0, -1));
88 if (TileY(tile
) >= 1 && TileX(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY(-1, -1));
89 if (TileX(tile
) >= 1) TerraformAddDirtyTile(ts
, tile
+ TileDiffXY(-1, 0));
90 TerraformAddDirtyTile(ts
, tile
);
94 * Terraform the north corner of a tile to a specific height.
96 * @param ts TerraformerState.
98 * @param height Aimed height.
99 * @return Error code or cost.
101 static CommandCost
TerraformTileHeight(TerraformerState
*ts
, TileIndex tile
, int height
)
103 assert(tile
< MapSize());
105 /* Check range of destination height */
106 if (height
< 0) return_cmd_error(STR_ERROR_ALREADY_AT_SEA_LEVEL
);
107 if (height
> _settings_game
.construction
.max_heightlevel
) return_cmd_error(STR_ERROR_TOO_HIGH
);
110 * Check if the terraforming has any effect.
111 * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
112 * In this case the terraforming should fail. (Don't know why.)
114 if (height
== TerraformGetHeightOfTile(ts
, tile
)) return CMD_ERROR
;
116 /* Check "too close to edge of map". Only possible when freeform-edges is off. */
117 uint x
= TileX(tile
);
118 uint y
= TileY(tile
);
119 if (!_settings_game
.construction
.freeform_edges
&& ((x
<= 1) || (y
<= 1) || (x
>= MapMaxX() - 1) || (y
>= MapMaxY() - 1))) {
121 * Determine a sensible error tile
125 _terraform_err_tile
= TileXY(x
, y
);
126 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP
);
129 /* Mark incident tiles that are involved in the terraforming. */
130 TerraformAddDirtyTileAround(ts
, tile
);
132 /* Store the height modification */
133 TerraformSetHeightOfTile(ts
, tile
, height
);
135 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
138 total_cost
.AddCost(_price
[PR_TERRAFORM
]);
140 /* Recurse to neighboured corners if height difference is larger than 1 */
142 const TileIndexDiffC
*ttm
;
144 TileIndex orig_tile
= tile
;
145 static const TileIndexDiffC _terraform_tilepos
[] = {
146 { 1, 0}, // move to tile in SE
147 {-2, 0}, // undo last move, and move to tile in NW
148 { 1, 1}, // undo last move, and move to tile in SW
149 { 0, -2} // undo last move, and move to tile in NE
152 for (ttm
= _terraform_tilepos
; ttm
!= endof(_terraform_tilepos
); ttm
++) {
153 tile
+= ToTileIndexDiff(*ttm
);
155 if (tile
>= MapSize()) continue;
156 /* Make sure we don't wrap around the map */
157 if (Delta(TileX(orig_tile
), TileX(tile
)) == MapSizeX() - 1) continue;
158 if (Delta(TileY(orig_tile
), TileY(tile
)) == MapSizeY() - 1) continue;
160 /* Get TileHeight of neighboured tile as of current terraform progress */
161 int r
= TerraformGetHeightOfTile(ts
, tile
);
162 int height_diff
= height
- r
;
164 /* Is the height difference to the neighboured corner greater than 1? */
165 if (abs(height_diff
) > 1) {
166 /* Terraform the neighboured corner. The resulting height difference should be 1. */
167 height_diff
+= (height_diff
< 0 ? 1 : -1);
168 CommandCost cost
= TerraformTileHeight(ts
, tile
, r
+ height_diff
);
169 if (cost
.Failed()) return cost
;
170 total_cost
.AddCost(cost
);
180 * @param tile tile to terraform
181 * @param flags for this command type
182 * @param p1 corners to terraform (SLOPE_xxx)
183 * @param p2 direction; eg up (non-zero) or down (zero)
185 * @return the cost of this operation or an error
187 CommandCost
CmdTerraformLand(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
189 _terraform_err_tile
= INVALID_TILE
;
191 CommandCost
total_cost(EXPENSES_CONSTRUCTION
);
192 int direction
= (p2
!= 0 ? 1 : -1);
195 /* Compute the costs and the terraforming result in a model of the landscape */
196 if ((p1
& SLOPE_W
) != 0 && tile
+ TileDiffXY(1, 0) < MapSize()) {
197 TileIndex t
= tile
+ TileDiffXY(1, 0);
198 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
199 if (cost
.Failed()) return cost
;
200 total_cost
.AddCost(cost
);
203 if ((p1
& SLOPE_S
) != 0 && tile
+ TileDiffXY(1, 1) < MapSize()) {
204 TileIndex t
= tile
+ TileDiffXY(1, 1);
205 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
206 if (cost
.Failed()) return cost
;
207 total_cost
.AddCost(cost
);
210 if ((p1
& SLOPE_E
) != 0 && tile
+ TileDiffXY(0, 1) < MapSize()) {
211 TileIndex t
= tile
+ TileDiffXY(0, 1);
212 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
213 if (cost
.Failed()) return cost
;
214 total_cost
.AddCost(cost
);
217 if ((p1
& SLOPE_N
) != 0) {
218 TileIndex t
= tile
+ TileDiffXY(0, 0);
219 CommandCost cost
= TerraformTileHeight(&ts
, t
, TileHeight(t
) + direction
);
220 if (cost
.Failed()) return cost
;
221 total_cost
.AddCost(cost
);
224 /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface
225 * Pass == 0: Collect tileareas which are caused to be auto-cleared.
226 * Pass == 1: Collect the actual cost. */
227 for (int pass
= 0; pass
< 2; pass
++) {
228 for (TileIndexSet::const_iterator it
= ts
.dirty_tiles
.begin(); it
!= ts
.dirty_tiles
.end(); it
++) {
229 TileIndex tile
= *it
;
231 assert(tile
< MapSize());
232 /* MP_VOID tiles can be terraformed but as tunnels and bridges
233 * cannot go under / over these tiles they don't need checking. */
234 if (IsTileType(tile
, MP_VOID
)) continue;
236 /* Find new heights of tile corners */
237 int z_N
= TerraformGetHeightOfTile(&ts
, tile
+ TileDiffXY(0, 0));
238 int z_W
= TerraformGetHeightOfTile(&ts
, tile
+ TileDiffXY(1, 0));
239 int z_S
= TerraformGetHeightOfTile(&ts
, tile
+ TileDiffXY(1, 1));
240 int z_E
= TerraformGetHeightOfTile(&ts
, tile
+ TileDiffXY(0, 1));
242 /* Find min and max height of tile */
243 int z_min
= std::min({z_N
, z_W
, z_S
, z_E
});
244 int z_max
= std::max({z_N
, z_W
, z_S
, z_E
});
246 /* Compute tile slope */
247 Slope tileh
= (z_max
> z_min
+ 1 ? SLOPE_STEEP
: SLOPE_FLAT
);
248 if (z_W
> z_min
) tileh
|= SLOPE_W
;
249 if (z_S
> z_min
) tileh
|= SLOPE_S
;
250 if (z_E
> z_min
) tileh
|= SLOPE_E
;
251 if (z_N
> z_min
) tileh
|= SLOPE_N
;
254 /* Check if bridge would take damage */
255 if (IsBridgeAbove(tile
)) {
256 int bridge_height
= GetBridgeHeight(GetSouthernBridgeEnd(tile
));
258 /* Check if bridge would take damage. */
259 if (direction
== 1 && bridge_height
<= z_max
) {
260 _terraform_err_tile
= tile
; // highlight the tile under the bridge
261 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST
);
264 /* Is the bridge above not too high afterwards? */
265 if (direction
== -1 && bridge_height
> (z_min
+ _settings_game
.construction
.max_bridge_height
)) {
266 _terraform_err_tile
= tile
;
267 return_cmd_error(STR_ERROR_BRIDGE_TOO_HIGH_AFTER_LOWER_LAND
);
270 /* Check if tunnel would take damage */
271 if (direction
== -1 && IsTunnelInWay(tile
, z_min
)) {
272 _terraform_err_tile
= tile
; // highlight the tile above the tunnel
273 return_cmd_error(STR_ERROR_EXCAVATION_WOULD_DAMAGE
);
277 /* Is the tile already cleared? */
278 const ClearedObjectArea
*coa
= FindClearedObject(tile
);
279 bool indirectly_cleared
= coa
!= nullptr && coa
->first_tile
!= tile
;
281 /* Check tiletype-specific things, and add extra-cost */
282 const bool curr_gen
= _generating_world
;
283 if (_game_mode
== GM_EDITOR
) _generating_world
= true; // used to create green terraformed land
284 DoCommandFlag tile_flags
= flags
| DC_AUTO
| DC_FORCE_CLEAR_TILE
;
286 tile_flags
&= ~DC_EXEC
;
287 tile_flags
|= DC_NO_MODIFY_TOWN_RATING
;
290 if (indirectly_cleared
) {
291 cost
= DoCommand(tile
, 0, 0, tile_flags
, CMD_LANDSCAPE_CLEAR
);
293 cost
= _tile_type_procs
[GetTileType(tile
)]->terraform_tile_proc(tile
, tile_flags
, z_min
, tileh
);
295 _generating_world
= curr_gen
;
297 _terraform_err_tile
= tile
;
300 if (pass
== 1) total_cost
.AddCost(cost
);
304 Company
*c
= Company::GetIfValid(_current_company
);
305 if (c
!= nullptr && GB(c
->terraform_limit
, 16, 16) < ts
.tile_to_new_height
.size()) {
306 return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED
);
309 if (flags
& DC_EXEC
) {
310 /* Mark affected areas dirty. */
311 for (TileIndexSet::const_iterator it
= ts
.dirty_tiles
.begin(); it
!= ts
.dirty_tiles
.end(); it
++) {
312 MarkTileDirtyByTile(*it
);
313 TileIndexToHeightMap::const_iterator new_height
= ts
.tile_to_new_height
.find(tile
);
314 if (new_height
== ts
.tile_to_new_height
.end()) continue;
315 MarkTileDirtyByTile(*it
, 0, new_height
->second
);
318 /* change the height */
319 for (TileIndexToHeightMap::const_iterator it
= ts
.tile_to_new_height
.begin();
320 it
!= ts
.tile_to_new_height
.end(); it
++) {
321 TileIndex tile
= it
->first
;
322 int height
= it
->second
;
324 SetTileHeight(tile
, (uint
)height
);
327 if (c
!= nullptr) c
->terraform_limit
-= (uint32
)ts
.tile_to_new_height
.size() << 16;
334 * Levels a selected (rectangle) area of land
335 * @param tile end tile of area-drag
336 * @param flags for this command type
337 * @param p1 start tile of area drag
338 * @param p2 various bitstuffed data.
339 * bit 0: Whether to use the Orthogonal (0) or Diagonal (1) iterator.
340 * bits 1 - 2: Mode of leveling \c LevelMode.
342 * @return the cost of this operation or an error
344 CommandCost
CmdLevelLand(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
346 if (p1
>= MapSize()) return CMD_ERROR
;
348 _terraform_err_tile
= INVALID_TILE
;
350 /* remember level height */
351 uint oldh
= TileHeight(p1
);
353 /* compute new height */
355 LevelMode lm
= (LevelMode
)GB(p2
, 1, 2);
357 case LM_LEVEL
: break;
358 case LM_RAISE
: h
++; break;
359 case LM_LOWER
: h
--; break;
360 default: return CMD_ERROR
;
363 /* Check range of destination height */
364 if (h
> _settings_game
.construction
.max_heightlevel
) return_cmd_error((oldh
== 0) ? STR_ERROR_ALREADY_AT_SEA_LEVEL
: STR_ERROR_TOO_HIGH
);
366 Money money
= GetAvailableMoneyForCommand();
367 CommandCost
cost(EXPENSES_CONSTRUCTION
);
368 CommandCost
last_error(lm
== LM_LEVEL
? STR_ERROR_ALREADY_LEVELLED
: INVALID_STRING_ID
);
369 bool had_success
= false;
371 const Company
*c
= Company::GetIfValid(_current_company
);
372 int limit
= (c
== nullptr ? INT32_MAX
: GB(c
->terraform_limit
, 16, 16));
373 if (limit
== 0) return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED
);
375 TileIterator
*iter
= HasBit(p2
, 0) ? (TileIterator
*)new DiagonalTileIterator(tile
, p1
) : new OrthogonalTileIterator(tile
, p1
);
376 for (; *iter
!= INVALID_TILE
; ++(*iter
)) {
378 uint curh
= TileHeight(t
);
380 CommandCost ret
= DoCommand(t
, SLOPE_N
, (curh
> h
) ? 0 : 1, flags
& ~DC_EXEC
, CMD_TERRAFORM_LAND
);
384 /* Did we reach the limit? */
385 if (ret
.GetErrorMessage() == STR_ERROR_TERRAFORM_LIMIT_REACHED
) limit
= 0;
389 if (flags
& DC_EXEC
) {
390 money
-= ret
.GetCost();
392 _additional_cash_required
= ret
.GetCost();
396 DoCommand(t
, SLOPE_N
, (curh
> h
) ? 0 : 1, flags
, CMD_TERRAFORM_LAND
);
398 /* When we're at the terraform limit we better bail (unneeded) testing as well.
399 * This will probably cause the terraforming cost to be underestimated, but only
400 * when it's near the terraforming limit. Even then, the estimation is
401 * completely off due to it basically counting terraforming double, so it being
402 * cut off earlier might even give a better estimate in some cases. */
410 curh
+= (curh
> h
) ? -1 : 1;
414 if (limit
<= 0) break;
418 return had_success
? cost
: last_error
;