Also scroll tile separators in the train depot
[openttd/fttd.git] / src / terraform_cmd.cpp
blobfa117f99a5069900e0ef20cb20a2a9438ded258b
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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 */
10 /** @file terraform_cmd.cpp Commands related to terraforming. */
12 #include "stdafx.h"
13 #include "command_func.h"
14 #include "map/zoneheight.h"
15 #include "map/tunnel.h"
16 #include "map/bridge.h"
17 #include "bridge.h"
18 #include "viewport_func.h"
19 #include "genworld.h"
20 #include "object_base.h"
21 #include "company_base.h"
22 #include "company_func.h"
23 #include "landscape_type.h"
25 #include "table/strings.h"
27 #include <map>
28 #include <set>
30 /** Set of tiles. */
31 typedef std::set<TileIndex> TileIndexSet;
32 /** Mapping of tiles to their height. */
33 typedef std::map<TileIndex, int> TileIndexToHeightMap;
35 /** State of the terraforming. */
36 struct TerraformerState {
37 TileIndexSet dirty_tiles; ///< The tiles that need to be redrawn.
38 TileIndexToHeightMap tile_to_new_height; ///< The tiles for which the height has changed.
41 TileIndex _terraform_err_tile; ///< first tile we couldn't terraform
43 /**
44 * Gets the TileHeight (height of north corner) of a tile as of current terraforming progress.
46 * @param ts TerraformerState.
47 * @param tile Tile.
48 * @return TileHeight.
50 static int TerraformGetHeightOfTile(const TerraformerState *ts, TileIndex tile)
52 TileIndexToHeightMap::const_iterator it = ts->tile_to_new_height.find(tile);
53 return it != ts->tile_to_new_height.end() ? it->second : TileHeight(tile);
56 /**
57 * Stores the TileHeight (height of north corner) of a tile in a TerraformerState.
59 * @param ts TerraformerState.
60 * @param tile Tile.
61 * @param height New TileHeight.
63 static void TerraformSetHeightOfTile(TerraformerState *ts, TileIndex tile, int height)
65 ts->tile_to_new_height[tile] = height;
68 /**
69 * Adds a tile to the "tile_table" in a TerraformerState.
71 * @param ts TerraformerState.
72 * @param tile Tile.
73 * @ingroup dirty
75 static void TerraformAddDirtyTile(TerraformerState *ts, TileIndex tile)
77 ts->dirty_tiles.insert(tile);
80 /**
81 * Adds all tiles that incident with the north corner of a specific tile to the "tile_table" in a TerraformerState.
83 * @param ts TerraformerState.
84 * @param tile Tile.
85 * @ingroup dirty
87 static void TerraformAddDirtyTileAround(TerraformerState *ts, TileIndex tile)
89 /* Make sure all tiles passed to TerraformAddDirtyTile are within [0, MapSize()] */
90 if (TileY(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY( 0, -1));
91 if (TileY(tile) >= 1 && TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, -1));
92 if (TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, 0));
93 TerraformAddDirtyTile(ts, tile);
96 /**
97 * Terraform the north corner of a tile to a specific height.
99 * @param ts TerraformerState.
100 * @param tile Tile.
101 * @param height Aimed height.
102 * @return Error code or cost.
104 static CommandCost TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height)
106 assert(tile < MapSize());
108 /* Check range of destination height */
109 if (height < 0) return_cmd_error(STR_ERROR_ALREADY_AT_SEA_LEVEL);
110 if (height > _settings_game.construction.max_heightlevel) return_cmd_error(STR_ERROR_TOO_HIGH);
113 * Check if the terraforming has any effect.
114 * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
115 * In this case the terraforming should fail. (Don't know why.)
117 if (height == TerraformGetHeightOfTile(ts, tile)) return CMD_ERROR;
119 /* Check "too close to edge of map". Only possible when freeform-edges is off. */
120 uint x = TileX(tile);
121 uint y = TileY(tile);
122 if (!_settings_game.construction.freeform_edges && ((x <= 1) || (y <= 1) || (x >= MapMaxX() - 1) || (y >= MapMaxY() - 1))) {
124 * Determine a sensible error tile
126 if (x == 1) x = 0;
127 if (y == 1) y = 0;
128 _terraform_err_tile = TileXY(x, y);
129 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP);
132 /* Mark incident tiles that are involved in the terraforming. */
133 TerraformAddDirtyTileAround(ts, tile);
135 /* Store the height modification */
136 TerraformSetHeightOfTile(ts, tile, height);
138 CommandCost total_cost(EXPENSES_CONSTRUCTION);
140 /* Increment cost */
141 total_cost.AddCost(_price[PR_TERRAFORM]);
143 /* Recurse to neighboured corners if height difference is larger than 1 */
145 const CoordDiff *ttm;
147 TileIndex orig_tile = tile;
148 static const CoordDiff _terraform_tilepos[] = {
149 { 1, 0}, // move to tile in SE
150 {-2, 0}, // undo last move, and move to tile in NW
151 { 1, 1}, // undo last move, and move to tile in SW
152 { 0, -2} // undo last move, and move to tile in NE
155 for (ttm = _terraform_tilepos; ttm != endof(_terraform_tilepos); ttm++) {
156 tile += ToTileIndexDiff(*ttm);
158 if (tile >= MapSize()) continue;
159 /* Make sure we don't wrap around the map */
160 if (Delta(TileX(orig_tile), TileX(tile)) == MapSizeX() - 1) continue;
161 if (Delta(TileY(orig_tile), TileY(tile)) == MapSizeY() - 1) continue;
163 /* Get TileHeight of neighboured tile as of current terraform progress */
164 int r = TerraformGetHeightOfTile(ts, tile);
165 int height_diff = height - r;
167 /* Is the height difference to the neighboured corner greater than 1? */
168 if (abs(height_diff) > 1) {
169 /* Terraform the neighboured corner. The resulting height difference should be 1. */
170 height_diff += (height_diff < 0 ? 1 : -1);
171 CommandCost cost = TerraformTileHeight(ts, tile, r + height_diff);
172 if (cost.Failed()) return cost;
173 total_cost.AddCost(cost);
178 return total_cost;
182 * Terraform land
183 * @param tile tile to terraform
184 * @param flags for this command type
185 * @param p1 corners to terraform (SLOPE_xxx)
186 * @param p2 direction; eg up (non-zero) or down (zero)
187 * @param text unused
188 * @return the cost of this operation or an error
190 CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
192 _terraform_err_tile = INVALID_TILE;
194 CommandCost total_cost(EXPENSES_CONSTRUCTION);
195 int direction = HasBit(p2, 0) ? 1 : -1;
196 TerraformerState ts;
198 /* Compute the costs and the terraforming result in a model of the landscape */
199 if ((p1 & SLOPE_W) != 0 && tile + TileDiffXY(1, 0) < MapSize()) {
200 TileIndex t = tile + TileDiffXY(1, 0);
201 CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
202 if (cost.Failed()) return cost;
203 total_cost.AddCost(cost);
206 if ((p1 & SLOPE_S) != 0 && tile + TileDiffXY(1, 1) < MapSize()) {
207 TileIndex t = tile + TileDiffXY(1, 1);
208 CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
209 if (cost.Failed()) return cost;
210 total_cost.AddCost(cost);
213 if ((p1 & SLOPE_E) != 0 && tile + TileDiffXY(0, 1) < MapSize()) {
214 TileIndex t = tile + TileDiffXY(0, 1);
215 CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
216 if (cost.Failed()) return cost;
217 total_cost.AddCost(cost);
220 if ((p1 & SLOPE_N) != 0) {
221 TileIndex t = tile + TileDiffXY(0, 0);
222 CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
223 if (cost.Failed()) return cost;
224 total_cost.AddCost(cost);
227 /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface
228 * Pass == 0: Collect tileareas which are caused to be auto-cleared.
229 * Pass == 1: Collect the actual cost. */
230 for (int pass = 0; pass < 2; pass++) {
231 for (TileIndexSet::const_iterator it = ts.dirty_tiles.begin(); it != ts.dirty_tiles.end(); it++) {
232 TileIndex tile = *it;
234 assert(tile < MapSize());
235 /* Void tiles can be terraformed but as tunnels and bridges
236 * cannot go under / over these tiles they don't need checking. */
237 if (IsVoidTile(tile)) continue;
239 /* Find new heights of tile corners */
240 int z_N = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 0));
241 int z_W = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 0));
242 int z_S = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 1));
243 int z_E = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 1));
245 /* Find min and max height of tile */
246 int z_min = min(min(z_N, z_W), min(z_S, z_E));
247 int z_max = max(max(z_N, z_W), max(z_S, z_E));
249 /* Compute tile slope */
250 Slope tileh = (z_max > z_min + 1 ? SLOPE_STEEP : SLOPE_FLAT);
251 if (z_W > z_min) tileh |= SLOPE_W;
252 if (z_S > z_min) tileh |= SLOPE_S;
253 if (z_E > z_min) tileh |= SLOPE_E;
254 if (z_N > z_min) tileh |= SLOPE_N;
256 if (pass == 0) {
257 /* Check if bridge would take damage */
258 if (HasBridgeAbove(tile)) {
259 int bridge_height = GetBridgeHeight(GetSouthernBridgeEnd(tile));
261 /* Check if bridge would take damage. */
262 if (direction == 1 && bridge_height <= z_max) {
263 _terraform_err_tile = tile; // highlight the tile under the bridge
264 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
267 /* Is the bridge above not too high afterwards? */
268 if (direction == -1 && bridge_height > (z_min + _settings_game.construction.max_bridge_height)) {
269 _terraform_err_tile = tile;
270 return_cmd_error(STR_ERROR_BRIDGE_TOO_HIGH_AFTER_LOWER_LAND);
273 /* Check if tunnel would take damage */
274 if (direction == -1 && IsTunnelInWay(tile, z_min)) {
275 _terraform_err_tile = tile; // highlight the tile above the tunnel
276 return_cmd_error(STR_ERROR_EXCAVATION_WOULD_DAMAGE);
280 /* Is the tile already cleared? */
281 const ClearedObjectArea *coa = FindClearedObject(tile);
282 bool indirectly_cleared = coa != NULL && coa->first_tile != tile;
284 /* Check tiletype-specific things, and add extra-cost */
285 const bool curr_gen = _generating_world;
286 if (_game_mode == GM_EDITOR) _generating_world = true; // used to create green terraformed land
287 DoCommandFlag tile_flags = flags | DC_AUTO | DC_FORCE_CLEAR_TILE;
288 if (pass == 0) {
289 tile_flags &= ~DC_EXEC;
290 tile_flags |= DC_NO_MODIFY_TOWN_RATING;
292 CommandCost cost;
293 if (indirectly_cleared) {
294 cost = DoCommand(tile, 0, 0, tile_flags, CMD_LANDSCAPE_CLEAR);
295 } else {
296 cost = GetTileProcs(tile)->terraform_tile_proc(tile, tile_flags, z_min, tileh);
298 _generating_world = curr_gen;
299 if (cost.Failed()) {
300 _terraform_err_tile = tile;
301 return cost;
303 if (pass == 1) total_cost.AddCost(cost);
307 Company *c = Company::GetIfValid(_current_company);
308 if (c != NULL && GB(c->terraform_limit, 16, 16) < ts.tile_to_new_height.size()) {
309 return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
312 if (flags & DC_EXEC) {
313 /* change the height */
314 for (TileIndexToHeightMap::const_iterator it = ts.tile_to_new_height.begin();
315 it != ts.tile_to_new_height.end(); it++) {
316 TileIndex tile = it->first;
317 int height = it->second;
319 SetTileHeight(tile, (uint)height);
322 /* Finally mark the dirty tiles dirty */
323 for (TileIndexSet::const_iterator it = ts.dirty_tiles.begin(); it != ts.dirty_tiles.end(); it++) {
324 MarkTileDirtyByTile(*it);
326 int height = TerraformGetHeightOfTile(&ts, *it);
328 /* Now, if we alter the height of the map edge, we need to take care
329 * about repainting the affected areas outside map as well.
330 * Remember:
331 * Outside map, we assume that our landscape descends to
332 * height zero as fast as possible.
333 * Those simulated tiles (they don't exist as datastructure,
334 * only as concept in code) need to be repainted properly,
335 * otherwise we will get ugly glitches.
337 * Furthermore, note that we have to take care about the possibility,
338 * that landscape was higher before the change,
339 * so also tiles a bit outside need to be repainted.
341 int x = TileX(*it);
342 int y = TileY(*it);
343 if (x == 0) {
344 if (y == 0) {
345 /* Height of the northern corner is altered. */
346 for (int cx = 0; cx >= -height - 1; cx--) {
347 for (int cy = 0; cy >= -height - 1; cy--) {
348 /* This means, tiles in the sector north of that
349 * corner need to be repainted.
351 if (cx + cy >= -height - 2) {
352 /* But only tiles that actually might have changed. */
353 MarkTileDirtyByTileOutsideMap(cx, cy);
357 } else if (y < (int)MapMaxY()) {
358 for (int cx = 0; cx >= -height - 1; cx--) {
359 MarkTileDirtyByTileOutsideMap(cx, y);
361 } else {
362 for (int cx = 0; cx >= -height - 1; cx--) {
363 for (int cy = (int)MapMaxY(); cy <= (int)MapMaxY() + height + 1; cy++) {
364 if (cx + ((int)MapMaxY() - cy) >= -height - 2) {
365 MarkTileDirtyByTileOutsideMap(cx, cy);
370 } else if (x < (int)MapMaxX()) {
371 if (y == 0) {
372 for (int cy = 0; cy >= -height - 1; cy--) {
373 MarkTileDirtyByTileOutsideMap(x, cy);
375 } else if (y < (int)MapMaxY()) {
376 /* Nothing to be done here, we are inside the map. */
377 } else {
378 for (int cy = (int)MapMaxY(); cy <= (int)MapMaxY() + height + 1; cy++) {
379 MarkTileDirtyByTileOutsideMap(x, cy);
382 } else {
383 if (y == 0) {
384 for (int cx = (int)MapMaxX(); cx <= (int)MapMaxX() + height + 1; cx++) {
385 for (int cy = 0; cy >= -height - 1; cy--) {
386 if (((int)MapMaxX() - cx) + cy >= -height - 2) {
387 MarkTileDirtyByTileOutsideMap(cx, cy);
391 } else if (y < (int)MapMaxY()) {
392 for (int cx = (int)MapMaxX(); cx <= (int)MapMaxX() + height + 1; cx++) {
393 MarkTileDirtyByTileOutsideMap(cx, y);
395 } else {
396 for (int cx = (int)MapMaxX(); cx <= (int)MapMaxX() + height + 1; cx++) {
397 for (int cy = (int)MapMaxY(); cy <= (int)MapMaxY() + height + 1; cy++) {
398 if (((int)MapMaxX() - cx) + ((int)MapMaxY() - cy) >= -height - 2) {
399 MarkTileDirtyByTileOutsideMap(cx, cy);
407 if (c != NULL) c->terraform_limit -= (uint32)ts.tile_to_new_height.size() << 16;
409 return total_cost;
414 * Levels a selected (rectangle) area of land
415 * @param tile end tile of area-drag
416 * @param flags for this command type
417 * @param p1 start tile of area drag
418 * @param p2 various bitstuffed data.
419 * bit 0: Whether to use the Orthogonal (0) or Diagonal (1) iterator.
420 * bits 1 - 2: Mode of leveling \c LevelMode.
421 * @param text unused
422 * @return the cost of this operation or an error
424 CommandCost CmdLevelLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
426 if (p1 >= MapSize()) return CMD_ERROR;
428 _terraform_err_tile = INVALID_TILE;
430 /* remember level height */
431 uint oldh = TileHeight(p1);
433 /* compute new height */
434 uint h = oldh;
435 LevelMode lm = (LevelMode)GB(p2, 1, 2);
436 switch (lm) {
437 case LM_LEVEL: break;
438 case LM_RAISE: h++; break;
439 case LM_LOWER: h--; break;
440 default: return CMD_ERROR;
443 /* Check range of destination height */
444 if (h > _settings_game.construction.max_heightlevel) return_cmd_error((oldh == 0) ? STR_ERROR_ALREADY_AT_SEA_LEVEL : STR_ERROR_TOO_HIGH);
446 Money money = GetAvailableMoneyForCommand();
447 CommandCost cost(EXPENSES_CONSTRUCTION);
448 CommandCost last_error(lm == LM_LEVEL ? STR_ERROR_ALREADY_LEVELLED : INVALID_STRING_ID);
449 bool had_success = false;
451 const Company *c = Company::GetIfValid(_current_company);
452 int limit = (c == NULL ? INT32_MAX : GB(c->terraform_limit, 16, 16));
453 if (limit == 0) return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
455 TileIterator *iter = HasBit(p2, 0) ? (TileIterator *)new DiagonalTileIterator(tile, p1) : new OrthogonalTileIterator(TileArea (tile, p1));
456 for (; *iter != INVALID_TILE; ++(*iter)) {
457 TileIndex t = *iter;
458 uint curh = TileHeight(t);
459 while (curh != h) {
460 CommandCost ret = DoCommand(t, SLOPE_N, (curh > h) ? 0 : 1, flags & ~DC_EXEC, CMD_TERRAFORM_LAND);
461 if (ret.Failed()) {
462 last_error = ret;
464 /* Did we reach the limit? */
465 if (ret.GetErrorMessage() == STR_ERROR_TERRAFORM_LIMIT_REACHED) limit = 0;
466 break;
469 if (flags & DC_EXEC) {
470 money -= ret.GetCost();
471 if (money < 0) {
472 _additional_cash_required = ret.GetCost();
473 delete iter;
474 return cost;
476 DoCommand(t, SLOPE_N, (curh > h) ? 0 : 1, flags, CMD_TERRAFORM_LAND);
477 } else {
478 /* When we're at the terraform limit we better bail (unneeded) testing as well.
479 * This will probably cause the terraforming cost to be underestimated, but only
480 * when it's near the terraforming limit. Even then, the estimation is
481 * completely off due to it basically counting terraforming double, so it being
482 * cut off earlier might even give a better estimate in some cases. */
483 if (--limit <= 0) {
484 had_success = true;
485 break;
489 cost.AddCost(ret);
490 curh += (curh > h) ? -1 : 1;
491 had_success = true;
494 if (limit <= 0) break;
497 delete iter;
498 return had_success ? cost : last_error;