(svn r25652) -Fix: Improve text caret movement for complex scripts.
[openttd/fttd.git] / src / terraform_cmd.cpp
blob8c0c63ac0714271a54497c97e71c1156a39b0a35
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 "tunnel_map.h"
15 #include "bridge_map.h"
16 #include "viewport_func.h"
17 #include "genworld.h"
18 #include "object_base.h"
19 #include "company_base.h"
20 #include "company_func.h"
22 #include "table/strings.h"
25 * In one terraforming command all four corners of a initial tile can be raised/lowered (though this is not available to the player).
26 * The maximal amount of height modifications is achieved when raising a complete flat land from sea level to MAX_TILE_HEIGHT or vice versa.
27 * This affects all corners with a manhatten distance smaller than MAX_TILE_HEIGHT to one of the initial 4 corners.
28 * Their maximal amount is computed to 4 * \sum_{i=1}^{h_max} i = 2 * h_max * (h_max + 1).
30 static const int TERRAFORMER_MODHEIGHT_SIZE = 2 * MAX_TILE_HEIGHT * (MAX_TILE_HEIGHT + 1);
33 * The maximal amount of affected tiles (i.e. the tiles that incident with one of the corners above, is computed similar to
34 * 1 + 4 * \sum_{i=1}^{h_max} (i+1) = 1 + 2 * h_max + (h_max + 3).
36 static const int TERRAFORMER_TILE_TABLE_SIZE = 1 + 2 * MAX_TILE_HEIGHT * (MAX_TILE_HEIGHT + 3);
38 struct TerraformerHeightMod {
39 TileIndex tile; ///< Referenced tile.
40 byte height; ///< New TileHeight (height of north corner) of the tile.
43 struct TerraformerState {
44 int modheight_count; ///< amount of entries in "modheight".
45 int tile_table_count; ///< amount of entries in "tile_table".
47 /**
48 * Dirty tiles, i.e.\ at least one corner changed.
50 * This array contains the tiles which are or will be marked as dirty.
52 * @ingroup dirty
54 TileIndex tile_table[TERRAFORMER_TILE_TABLE_SIZE];
55 TerraformerHeightMod modheight[TERRAFORMER_MODHEIGHT_SIZE]; ///< Height modifications.
58 TileIndex _terraform_err_tile; ///< first tile we couldn't terraform
60 /**
61 * Gets the TileHeight (height of north corner) of a tile as of current terraforming progress.
63 * @param ts TerraformerState.
64 * @param tile Tile.
65 * @return TileHeight.
67 static int TerraformGetHeightOfTile(const TerraformerState *ts, TileIndex tile)
69 const TerraformerHeightMod *mod = ts->modheight;
71 for (int count = ts->modheight_count; count != 0; count--, mod++) {
72 if (mod->tile == tile) return mod->height;
75 /* TileHeight unchanged so far, read value from map. */
76 return TileHeight(tile);
79 /**
80 * Stores the TileHeight (height of north corner) of a tile in a TerraformerState.
82 * @param ts TerraformerState.
83 * @param tile Tile.
84 * @param height New TileHeight.
86 static void TerraformSetHeightOfTile(TerraformerState *ts, TileIndex tile, int height)
88 /* Find tile in the "modheight" table.
89 * Note: In a normal user-terraform command the tile will not be found in the "modheight" table.
90 * But during house- or industry-construction multiple corners can be terraformed at once. */
91 TerraformerHeightMod *mod = ts->modheight;
92 int count = ts->modheight_count;
94 while ((count > 0) && (mod->tile != tile)) {
95 mod++;
96 count--;
99 /* New entry? */
100 if (count == 0) {
101 assert(ts->modheight_count < TERRAFORMER_MODHEIGHT_SIZE);
102 ts->modheight_count++;
105 /* Finally store the new value */
106 mod->tile = tile;
107 mod->height = (byte)height;
111 * Adds a tile to the "tile_table" in a TerraformerState.
113 * @param ts TerraformerState.
114 * @param tile Tile.
115 * @ingroup dirty
117 static void TerraformAddDirtyTile(TerraformerState *ts, TileIndex tile)
119 int count = ts->tile_table_count;
121 for (TileIndex *t = ts->tile_table; count != 0; count--, t++) {
122 if (*t == tile) return;
125 assert(ts->tile_table_count < TERRAFORMER_TILE_TABLE_SIZE);
127 ts->tile_table[ts->tile_table_count++] = tile;
131 * Adds all tiles that incident with the north corner of a specific tile to the "tile_table" in a TerraformerState.
133 * @param ts TerraformerState.
134 * @param tile Tile.
135 * @ingroup dirty
137 static void TerraformAddDirtyTileAround(TerraformerState *ts, TileIndex tile)
139 /* Make sure all tiles passed to TerraformAddDirtyTile are within [0, MapSize()] */
140 if (TileY(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY( 0, -1));
141 if (TileY(tile) >= 1 && TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, -1));
142 if (TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, 0));
143 TerraformAddDirtyTile(ts, tile);
147 * Terraform the north corner of a tile to a specific height.
149 * @param ts TerraformerState.
150 * @param tile Tile.
151 * @param height Aimed height.
152 * @return Error code or cost.
154 static CommandCost TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height)
156 assert(tile < MapSize());
158 /* Check range of destination height */
159 if (height < 0) return_cmd_error(STR_ERROR_ALREADY_AT_SEA_LEVEL);
160 if (height > (int)MAX_TILE_HEIGHT) return_cmd_error(STR_ERROR_TOO_HIGH);
163 * Check if the terraforming has any effect.
164 * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
165 * In this case the terraforming should fail. (Don't know why.)
167 if (height == TerraformGetHeightOfTile(ts, tile)) return CMD_ERROR;
169 /* Check "too close to edge of map". Only possible when freeform-edges is off. */
170 uint x = TileX(tile);
171 uint y = TileY(tile);
172 if (!_settings_game.construction.freeform_edges && ((x <= 1) || (y <= 1) || (x >= MapMaxX() - 1) || (y >= MapMaxY() - 1))) {
174 * Determine a sensible error tile
176 if (x == 1) x = 0;
177 if (y == 1) y = 0;
178 _terraform_err_tile = TileXY(x, y);
179 return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP);
182 /* Mark incident tiles that are involved in the terraforming. */
183 TerraformAddDirtyTileAround(ts, tile);
185 /* Store the height modification */
186 TerraformSetHeightOfTile(ts, tile, height);
188 CommandCost total_cost(EXPENSES_CONSTRUCTION);
190 /* Increment cost */
191 total_cost.AddCost(_price[PR_TERRAFORM]);
193 /* Recurse to neighboured corners if height difference is larger than 1 */
195 const TileIndexDiffC *ttm;
197 TileIndex orig_tile = tile;
198 static const TileIndexDiffC _terraform_tilepos[] = {
199 { 1, 0}, // move to tile in SE
200 {-2, 0}, // undo last move, and move to tile in NW
201 { 1, 1}, // undo last move, and move to tile in SW
202 { 0, -2} // undo last move, and move to tile in NE
205 for (ttm = _terraform_tilepos; ttm != endof(_terraform_tilepos); ttm++) {
206 tile += ToTileIndexDiff(*ttm);
208 if (tile >= MapSize()) continue;
209 /* Make sure we don't wrap around the map */
210 if (Delta(TileX(orig_tile), TileX(tile)) == MapSizeX() - 1) continue;
211 if (Delta(TileY(orig_tile), TileY(tile)) == MapSizeY() - 1) continue;
213 /* Get TileHeight of neighboured tile as of current terraform progress */
214 int r = TerraformGetHeightOfTile(ts, tile);
215 int height_diff = height - r;
217 /* Is the height difference to the neighboured corner greater than 1? */
218 if (abs(height_diff) > 1) {
219 /* Terraform the neighboured corner. The resulting height difference should be 1. */
220 height_diff += (height_diff < 0 ? 1 : -1);
221 CommandCost cost = TerraformTileHeight(ts, tile, r + height_diff);
222 if (cost.Failed()) return cost;
223 total_cost.AddCost(cost);
228 return total_cost;
232 * Terraform land
233 * @param tile tile to terraform
234 * @param flags for this command type
235 * @param p1 corners to terraform (SLOPE_xxx)
236 * @param p2 direction; eg up (non-zero) or down (zero)
237 * @param text unused
238 * @return the cost of this operation or an error
240 CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
242 _terraform_err_tile = INVALID_TILE;
244 CommandCost total_cost(EXPENSES_CONSTRUCTION);
245 int direction = (p2 != 0 ? 1 : -1);
246 TerraformerState ts;
248 ts.modheight_count = ts.tile_table_count = 0;
250 /* Compute the costs and the terraforming result in a model of the landscape */
251 if ((p1 & SLOPE_W) != 0 && tile + TileDiffXY(1, 0) < MapSize()) {
252 TileIndex t = tile + TileDiffXY(1, 0);
253 CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
254 if (cost.Failed()) return cost;
255 total_cost.AddCost(cost);
258 if ((p1 & SLOPE_S) != 0 && tile + TileDiffXY(1, 1) < MapSize()) {
259 TileIndex t = tile + TileDiffXY(1, 1);
260 CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
261 if (cost.Failed()) return cost;
262 total_cost.AddCost(cost);
265 if ((p1 & SLOPE_E) != 0 && tile + TileDiffXY(0, 1) < MapSize()) {
266 TileIndex t = tile + TileDiffXY(0, 1);
267 CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
268 if (cost.Failed()) return cost;
269 total_cost.AddCost(cost);
272 if ((p1 & SLOPE_N) != 0) {
273 TileIndex t = tile + TileDiffXY(0, 0);
274 CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
275 if (cost.Failed()) return cost;
276 total_cost.AddCost(cost);
279 /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface
280 * Pass == 0: Collect tileareas which are caused to be auto-cleared.
281 * Pass == 1: Collect the actual cost. */
282 for (int pass = 0; pass < 2; pass++) {
283 TileIndex *ti = ts.tile_table;
285 for (int count = ts.tile_table_count; count != 0; count--, ti++) {
286 TileIndex tile = *ti;
288 assert(tile < MapSize());
289 /* MP_VOID tiles can be terraformed but as tunnels and bridges
290 * cannot go under / over these tiles they don't need checking. */
291 if (IsTileType(tile, MP_VOID)) continue;
293 /* Find new heights of tile corners */
294 int z_N = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 0));
295 int z_W = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 0));
296 int z_S = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 1));
297 int z_E = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 1));
299 /* Find min and max height of tile */
300 int z_min = min(min(z_N, z_W), min(z_S, z_E));
301 int z_max = max(max(z_N, z_W), max(z_S, z_E));
303 /* Compute tile slope */
304 Slope tileh = (z_max > z_min + 1 ? SLOPE_STEEP : SLOPE_FLAT);
305 if (z_W > z_min) tileh |= SLOPE_W;
306 if (z_S > z_min) tileh |= SLOPE_S;
307 if (z_E > z_min) tileh |= SLOPE_E;
308 if (z_N > z_min) tileh |= SLOPE_N;
310 if (pass == 0) {
311 /* Check if bridge would take damage */
312 if (direction == 1 && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile) &&
313 GetBridgeHeight(GetSouthernBridgeEnd(tile)) <= z_max) {
314 _terraform_err_tile = tile; // highlight the tile under the bridge
315 return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
317 /* Check if tunnel would take damage */
318 if (direction == -1 && IsTunnelInWay(tile, z_min)) {
319 _terraform_err_tile = tile; // highlight the tile above the tunnel
320 return_cmd_error(STR_ERROR_EXCAVATION_WOULD_DAMAGE);
324 /* Is the tile already cleared? */
325 const ClearedObjectArea *coa = FindClearedObject(tile);
326 bool indirectly_cleared = coa != NULL && coa->first_tile != tile;
328 /* Check tiletype-specific things, and add extra-cost */
329 const bool curr_gen = _generating_world;
330 if (_game_mode == GM_EDITOR) _generating_world = true; // used to create green terraformed land
331 DoCommandFlag tile_flags = flags | DC_AUTO | DC_FORCE_CLEAR_TILE;
332 if (pass == 0) {
333 tile_flags &= ~DC_EXEC;
334 tile_flags |= DC_NO_MODIFY_TOWN_RATING;
336 CommandCost cost;
337 if (indirectly_cleared) {
338 cost = DoCommand(tile, 0, 0, tile_flags, CMD_LANDSCAPE_CLEAR);
339 } else {
340 cost = _tile_type_procs[GetTileType(tile)]->terraform_tile_proc(tile, tile_flags, z_min, tileh);
342 _generating_world = curr_gen;
343 if (cost.Failed()) {
344 _terraform_err_tile = tile;
345 return cost;
347 if (pass == 1) total_cost.AddCost(cost);
351 Company *c = Company::GetIfValid(_current_company);
352 if (c != NULL && (int)GB(c->terraform_limit, 16, 16) < ts.modheight_count) {
353 return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
356 if (flags & DC_EXEC) {
357 /* change the height */
359 int count;
360 TerraformerHeightMod *mod;
362 mod = ts.modheight;
363 for (count = ts.modheight_count; count != 0; count--, mod++) {
364 TileIndex til = mod->tile;
366 SetTileHeight(til, mod->height);
370 /* finally mark the dirty tiles dirty */
372 int count;
373 TileIndex *ti = ts.tile_table;
374 for (count = ts.tile_table_count; count != 0; count--, ti++) {
375 MarkTileDirtyByTile(*ti);
379 if (c != NULL) c->terraform_limit -= ts.modheight_count << 16;
381 return total_cost;
386 * Levels a selected (rectangle) area of land
387 * @param tile end tile of area-drag
388 * @param flags for this command type
389 * @param p1 start tile of area drag
390 * @param p2 various bitstuffed data.
391 * bit 0: Whether to use the Orthogonal (0) or Diagonal (1) iterator.
392 * bits 1 - 2: Mode of leveling \c LevelMode.
393 * @param text unused
394 * @return the cost of this operation or an error
396 CommandCost CmdLevelLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
398 if (p1 >= MapSize()) return CMD_ERROR;
400 _terraform_err_tile = INVALID_TILE;
402 /* remember level height */
403 uint oldh = TileHeight(p1);
405 /* compute new height */
406 uint h = oldh;
407 LevelMode lm = (LevelMode)GB(p2, 1, 2);
408 switch (lm) {
409 case LM_LEVEL: break;
410 case LM_RAISE: h++; break;
411 case LM_LOWER: h--; break;
412 default: return CMD_ERROR;
415 /* Check range of destination height */
416 if (h > MAX_TILE_HEIGHT) return_cmd_error((oldh == 0) ? STR_ERROR_ALREADY_AT_SEA_LEVEL : STR_ERROR_TOO_HIGH);
418 Money money = GetAvailableMoneyForCommand();
419 CommandCost cost(EXPENSES_CONSTRUCTION);
420 CommandCost last_error(lm == LM_LEVEL ? STR_ERROR_ALREADY_LEVELLED : INVALID_STRING_ID);
421 bool had_success = false;
423 const Company *c = Company::GetIfValid(_current_company);
424 int limit = (c == NULL ? INT32_MAX : GB(c->terraform_limit, 16, 16));
425 if (limit == 0) return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
427 TileArea ta(tile, p1);
428 TileIterator *iter = HasBit(p2, 0) ? (TileIterator *)new DiagonalTileIterator(tile, p1) : new OrthogonalTileIterator(ta);
429 for (; *iter != INVALID_TILE; ++(*iter)) {
430 TileIndex t = *iter;
431 uint curh = TileHeight(t);
432 while (curh != h) {
433 CommandCost ret = DoCommand(t, SLOPE_N, (curh > h) ? 0 : 1, flags & ~DC_EXEC, CMD_TERRAFORM_LAND);
434 if (ret.Failed()) {
435 last_error = ret;
437 /* Did we reach the limit? */
438 if (ret.GetErrorMessage() == STR_ERROR_TERRAFORM_LIMIT_REACHED) limit = 0;
439 break;
442 if (flags & DC_EXEC) {
443 money -= ret.GetCost();
444 if (money < 0) {
445 _additional_cash_required = ret.GetCost();
446 delete iter;
447 return cost;
449 DoCommand(t, SLOPE_N, (curh > h) ? 0 : 1, flags, CMD_TERRAFORM_LAND);
450 } else {
451 /* When we're at the terraform limit we better bail (unneeded) testing as well.
452 * This will probably cause the terraforming cost to be underestimated, but only
453 * when it's near the terraforming limit. Even then, the estimation is
454 * completely off due to it basically counting terraforming double, so it being
455 * cut off earlier might even give a better estimate in some cases. */
456 if (--limit <= 0) {
457 had_success = true;
458 break;
462 cost.AddCost(ret);
463 curh += (curh > h) ? -1 : 1;
464 had_success = true;
467 if (limit <= 0) break;
470 delete iter;
471 return had_success ? cost : last_error;