terraform_cmd.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "command_func.h"
00014 #include "tunnel_map.h"
00015 #include "bridge_map.h"
00016 #include "viewport_func.h"
00017 #include "genworld.h"
00018 #include "object_base.h"
00019 #include "company_base.h"
00020 #include "company_func.h"
00021 //#include "settings_type.h"
00022 
00023 #include "table/strings.h"
00024 
00025 /*
00026  * In one terraforming command all four corners of a initial tile can be raised/lowered (though this is not available to the player).
00027  * The maximal amount of height modifications is archieved when raising a complete flat land from sea level to MAX_TILE_HEIGHT or vice versa.
00028  * This affects all corners with a manhatten distance smaller than MAX_TILE_HEIGHT to one of the initial 4 corners.
00029  * Their maximal amount is computed to 4 * \sum_{i=1}^{h_max} i  =  2 * h_max * (h_max + 1).
00030  */
00031 static const int TERRAFORMER_MODHEIGHT_SIZE = 2 * MAX_TILE_HEIGHT * (MAX_TILE_HEIGHT + 1);
00032 
00033 /*
00034  * The maximal amount of affected tiles (i.e. the tiles that incident with one of the corners above, is computed similiar to
00035  * 1 + 4 * \sum_{i=1}^{h_max} (i+1)  =  1 + 2 * h_max + (h_max + 3).
00036  */
00037 static const int TERRAFORMER_TILE_TABLE_SIZE = 1 + 2 * MAX_TILE_HEIGHT * (MAX_TILE_HEIGHT + 3);
00038 
00039 struct TerraformerHeightMod {
00040   TileIndex tile;   
00041   byte height;      
00042 };
00043 
00044 struct TerraformerState {
00045   int modheight_count;  
00046   int tile_table_count; 
00047 
00055   TileIndex tile_table[TERRAFORMER_TILE_TABLE_SIZE];
00056   TerraformerHeightMod modheight[TERRAFORMER_MODHEIGHT_SIZE];  
00057 };
00058 
00059 TileIndex _terraform_err_tile; 
00060 
00068 static int TerraformGetHeightOfTile(const TerraformerState *ts, TileIndex tile)
00069 {
00070   const TerraformerHeightMod *mod = ts->modheight;
00071 
00072   for (int count = ts->modheight_count; count != 0; count--, mod++) {
00073     if (mod->tile == tile) return mod->height;
00074   }
00075 
00076   /* TileHeight unchanged so far, read value from map. */
00077   return TileHeight(tile);
00078 }
00079 
00087 static void TerraformSetHeightOfTile(TerraformerState *ts, TileIndex tile, int height)
00088 {
00089   /* Find tile in the "modheight" table.
00090    * Note: In a normal user-terraform command the tile will not be found in the "modheight" table.
00091    *       But during house- or industry-construction multiple corners can be terraformed at once. */
00092   TerraformerHeightMod *mod = ts->modheight;
00093   int count = ts->modheight_count;
00094 
00095   while ((count > 0) && (mod->tile != tile)) {
00096     mod++;
00097     count--;
00098   }
00099 
00100   /* New entry? */
00101   if (count == 0) {
00102     assert(ts->modheight_count < TERRAFORMER_MODHEIGHT_SIZE);
00103     ts->modheight_count++;
00104   }
00105 
00106   /* Finally store the new value */
00107   mod->tile = tile;
00108   mod->height = (byte)height;
00109 }
00110 
00118 static void TerraformAddDirtyTile(TerraformerState *ts, TileIndex tile)
00119 {
00120   int count = ts->tile_table_count;
00121 
00122   for (TileIndex *t = ts->tile_table; count != 0; count--, t++) {
00123     if (*t == tile) return;
00124   }
00125 
00126   assert(ts->tile_table_count < TERRAFORMER_TILE_TABLE_SIZE);
00127 
00128   ts->tile_table[ts->tile_table_count++] = tile;
00129 }
00130 
00138 static void TerraformAddDirtyTileAround(TerraformerState *ts, TileIndex tile)
00139 {
00140   /* Make sure all tiles passed to TerraformAddDirtyTile are within [0, MapSize()] */
00141   if (TileY(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY( 0, -1));
00142   if (TileY(tile) >= 1 && TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, -1));
00143   if (TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1,  0));
00144   TerraformAddDirtyTile(ts, tile);
00145 }
00146 
00155 static CommandCost TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height)
00156 {
00157   assert(tile < MapSize());
00158 
00159   /* Check range of destination height */
00160   if (height < 0) return_cmd_error(STR_ERROR_ALREADY_AT_SEA_LEVEL);
00161   if (height > (int)MAX_TILE_HEIGHT) return_cmd_error(STR_ERROR_TOO_HIGH);
00162 
00163   /*
00164    * Check if the terraforming has any effect.
00165    * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
00166    * In this case the terraforming should fail. (Don't know why.)
00167    */
00168   if (height == TerraformGetHeightOfTile(ts, tile)) return CMD_ERROR;
00169 
00170   /* Check "too close to edge of map". Only possible when freeform-edges is off. */
00171   uint x = TileX(tile);
00172   uint y = TileY(tile);
00173   if (!_settings_game.construction.freeform_edges && ((x <= 1) || (y <= 1) || (x >= MapMaxX() - 1) || (y >= MapMaxY() - 1))) {
00174     /*
00175      * Determine a sensible error tile
00176      */
00177     if (x == 1) x = 0;
00178     if (y == 1) y = 0;
00179     _terraform_err_tile = TileXY(x, y);
00180     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP);
00181   }
00182 
00183   /* Don't terraform tiles on the wrong side of the map. */
00184   uint area = GetAreaByTile(tile);
00185   if (!_generating_world && area != (uint)_current_company + 1) return CommandCost();
00186 
00187   /* Mark incident tiles that are involved in the terraforming. */
00188   TerraformAddDirtyTileAround(ts, tile);
00189 
00190   /* Store the height modification */
00191   TerraformSetHeightOfTile(ts, tile, height);
00192 
00193   CommandCost total_cost(EXPENSES_CONSTRUCTION);
00194 
00195   /* Increment cost */
00196   total_cost.AddCost(_price[PR_TERRAFORM]);
00197 
00198   /* Recurse to neighboured corners if height difference is larger than 1 */
00199   {
00200     const TileIndexDiffC *ttm;
00201 
00202     TileIndex orig_tile = tile;
00203     static const TileIndexDiffC _terraform_tilepos[] = {
00204       { 1,  0}, // move to tile in SE
00205       {-2,  0}, // undo last move, and move to tile in NW
00206       { 1,  1}, // undo last move, and move to tile in SW
00207       { 0, -2}  // undo last move, and move to tile in NE
00208     };
00209 
00210     for (ttm = _terraform_tilepos; ttm != endof(_terraform_tilepos); ttm++) {
00211       tile += ToTileIndexDiff(*ttm);
00212 
00213       if (tile >= MapSize()) continue;
00214       /* Make sure we don't wrap around the map */
00215       if (Delta(TileX(orig_tile), TileX(tile)) == MapSizeX() - 1) continue;
00216       if (Delta(TileY(orig_tile), TileY(tile)) == MapSizeY() - 1) continue;
00217 
00218       /* Get TileHeight of neighboured tile as of current terraform progress */
00219       int r = TerraformGetHeightOfTile(ts, tile);
00220       int height_diff = height - r;
00221 
00222       /* Is the height difference to the neighboured corner greater than 1? */
00223       if (abs(height_diff) > 1) {
00224         /* Terraform the neighboured corner. The resulting height difference should be 1. */
00225         height_diff += (height_diff < 0 ? 1 : -1);
00226         CommandCost cost = TerraformTileHeight(ts, tile, r + height_diff);
00227         if (cost.Failed()) return cost;
00228         total_cost.AddCost(cost);
00229       }
00230     }
00231   }
00232 
00233   return total_cost;
00234 }
00235 
00245 CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00246 {
00247   _terraform_err_tile = INVALID_TILE;
00248 
00249   CommandCost total_cost(EXPENSES_CONSTRUCTION);
00250   int direction = (p2 != 0 ? 1 : -1);
00251   TerraformerState ts;
00252 
00253   ts.modheight_count = ts.tile_table_count = 0;
00254 
00255   /* Compute the costs and the terraforming result in a model of the landscape */
00256   if ((p1 & SLOPE_W) != 0 && tile + TileDiffXY(1, 0) < MapSize()) {
00257     TileIndex t = tile + TileDiffXY(1, 0);
00258     CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
00259     if (cost.Failed()) return cost;
00260     total_cost.AddCost(cost);
00261   }
00262 
00263   if ((p1 & SLOPE_S) != 0 && tile + TileDiffXY(1, 1) < MapSize()) {
00264     TileIndex t = tile + TileDiffXY(1, 1);
00265     CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
00266     if (cost.Failed()) return cost;
00267     total_cost.AddCost(cost);
00268   }
00269 
00270   if ((p1 & SLOPE_E) != 0 && tile + TileDiffXY(0, 1) < MapSize()) {
00271     TileIndex t = tile + TileDiffXY(0, 1);
00272     CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
00273     if (cost.Failed()) return cost;
00274     total_cost.AddCost(cost);
00275   }
00276 
00277   if ((p1 & SLOPE_N) != 0) {
00278     TileIndex t = tile + TileDiffXY(0, 0);
00279     CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
00280     if (cost.Failed()) return cost;
00281     total_cost.AddCost(cost);
00282   }
00283 
00284   /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface
00285    * Pass == 0: Collect tileareas which are caused to be auto-cleared.
00286    * Pass == 1: Collect the actual cost. */
00287   for (int pass = 0; pass < 2; pass++) {
00288     TileIndex *ti = ts.tile_table;
00289 
00290     for (int count = ts.tile_table_count; count != 0; count--, ti++) {
00291       TileIndex tile = *ti;
00292 
00293       assert(tile < MapSize());
00294       /* MP_VOID tiles can be terraformed but as tunnels and bridges
00295        * cannot go under / over these tiles they don't need checking. */
00296       if (IsTileType(tile, MP_VOID)) continue;
00297 
00298       /* Find new heights of tile corners */
00299       int z_N = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 0));
00300       int z_W = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 0));
00301       int z_S = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 1));
00302       int z_E = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 1));
00303 
00304       /* Find min and max height of tile */
00305       int z_min = min(min(z_N, z_W), min(z_S, z_E));
00306       int z_max = max(max(z_N, z_W), max(z_S, z_E));
00307 
00308       /* Compute tile slope */
00309       Slope tileh = (z_max > z_min + 1 ? SLOPE_STEEP : SLOPE_FLAT);
00310       if (z_W > z_min) tileh |= SLOPE_W;
00311       if (z_S > z_min) tileh |= SLOPE_S;
00312       if (z_E > z_min) tileh |= SLOPE_E;
00313       if (z_N > z_min) tileh |= SLOPE_N;
00314 
00315       if (pass == 0) {
00316         /* Check if bridge would take damage */
00317         if (direction == 1 && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile) &&
00318             GetBridgeHeight(GetSouthernBridgeEnd(tile)) <= z_max) {
00319           _terraform_err_tile = tile; // highlight the tile under the bridge
00320           return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00321         }
00322         /* Check if tunnel would take damage */
00323         if (direction == -1 && IsTunnelInWay(tile, z_min)) {
00324           _terraform_err_tile = tile; // highlight the tile above the tunnel
00325           return_cmd_error(STR_ERROR_EXCAVATION_WOULD_DAMAGE);
00326         }
00327       }
00328 
00329       /* Is the tile already cleared? */
00330       const ClearedObjectArea *coa = FindClearedObject(tile);
00331       bool indirectly_cleared = coa != NULL && coa->first_tile != tile;
00332 
00333       /* Check tiletype-specific things, and add extra-cost */
00334       const bool curr_gen = _generating_world;
00335       if (_game_mode == GM_EDITOR) _generating_world = true; // used to create green terraformed land
00336       DoCommandFlag tile_flags = flags | DC_AUTO | DC_FORCE_CLEAR_TILE;
00337       if (pass == 0) {
00338         tile_flags &= ~DC_EXEC;
00339         tile_flags |= DC_NO_MODIFY_TOWN_RATING;
00340       }
00341       CommandCost cost;
00342       if (indirectly_cleared) {
00343         cost = DoCommand(tile, 0, 0, tile_flags, CMD_LANDSCAPE_CLEAR);
00344       } else {
00345         cost = _tile_type_procs[GetTileType(tile)]->terraform_tile_proc(tile, tile_flags, z_min, tileh);
00346       }
00347       _generating_world = curr_gen;
00348       if (cost.Failed()) {
00349         _terraform_err_tile = tile;
00350         return cost;
00351       }
00352       if (pass == 1) total_cost.AddCost(cost);
00353     }
00354   }
00355 
00356   Company *c = Company::GetIfValid(_current_company);
00357   if (c != NULL && (int)GB(c->terraform_limit, 16, 16) < ts.modheight_count) {
00358     return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
00359   }
00360 
00361   if (flags & DC_EXEC) {
00362     /* change the height */
00363     {
00364       int count;
00365       TerraformerHeightMod *mod;
00366 
00367       mod = ts.modheight;
00368       for (count = ts.modheight_count; count != 0; count--, mod++) {
00369         TileIndex til = mod->tile;
00370 
00371         SetTileHeight(til, mod->height);
00372       }
00373     }
00374 
00375     /* finally mark the dirty tiles dirty */
00376     {
00377       int count;
00378       TileIndex *ti = ts.tile_table;
00379       for (count = ts.tile_table_count; count != 0; count--, ti++) {
00380         MarkTileDirtyByTile(*ti);
00381       }
00382     }
00383 
00384     if (c != NULL) c->terraform_limit -= ts.modheight_count << 16;
00385   }
00386   return total_cost;
00387 }
00388 
00389 
00401 CommandCost CmdLevelLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00402 {
00403   if (p1 >= MapSize()) return CMD_ERROR;
00404 
00405   _terraform_err_tile = INVALID_TILE;
00406 
00407   /* remember level height */
00408   uint oldh = TileHeight(p1);
00409 
00410   /* compute new height */
00411   uint h = oldh;
00412   LevelMode lm = (LevelMode)GB(p2, 1, 2);
00413   switch (lm) {
00414     case LM_LEVEL: break;
00415     case LM_RAISE: h++; break;
00416     case LM_LOWER: h--; break;
00417     default: return CMD_ERROR;
00418   }
00419 
00420   /* Check range of destination height */
00421   if (h > MAX_TILE_HEIGHT) return_cmd_error((oldh == 0) ? STR_ERROR_ALREADY_AT_SEA_LEVEL : STR_ERROR_TOO_HIGH);
00422 
00423   Money money = GetAvailableMoneyForCommand();
00424   CommandCost cost(EXPENSES_CONSTRUCTION);
00425   CommandCost last_error(lm == LM_LEVEL ? STR_ERROR_ALREADY_LEVELLED : INVALID_STRING_ID);
00426   bool had_success = false;
00427 
00428   const Company *c = Company::GetIfValid(_current_company);
00429   int limit = (c == NULL ? INT32_MAX : GB(c->terraform_limit, 16, 16));
00430   if (limit == 0) return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
00431 
00432   TileArea ta(tile, p1);
00433   TileIterator *iter = HasBit(p2, 0) ? (TileIterator *)new DiagonalTileIterator(tile, p1) : new OrthogonalTileIterator(ta);
00434   for (; *iter != INVALID_TILE; ++(*iter)) {
00435     TileIndex t = *iter;
00436     uint curh = TileHeight(t);
00437     while (curh != h) {
00438       CommandCost ret = DoCommand(t, SLOPE_N, (curh > h) ? 0 : 1, flags & ~DC_EXEC, CMD_TERRAFORM_LAND);
00439       if (ret.Failed()) {
00440         last_error = ret;
00441 
00442         /* Did we reach the limit? */
00443         if (ret.GetErrorMessage() == STR_ERROR_TERRAFORM_LIMIT_REACHED) limit = 0;
00444         break;
00445       }
00446 
00447       if (flags & DC_EXEC) {
00448         money -= ret.GetCost();
00449         if (money < 0) {
00450           _additional_cash_required = ret.GetCost();
00451           delete iter;
00452           return cost;
00453         }
00454         DoCommand(t, SLOPE_N, (curh > h) ? 0 : 1, flags, CMD_TERRAFORM_LAND);
00455       } else {
00456         /* When we're at the terraform limit we better bail (unneeded) testing as well.
00457          * This will probably cause the terraforming cost to be underestimated, but only
00458          * when it's near the terraforming limit. Even then, the estimation is
00459          * completely off due to it basically counting terraforming double, so it being
00460          * cut off earlier might even give a better estimate in some cases. */
00461         if (--limit <= 0) {
00462           had_success = true;
00463           break;
00464         }
00465       }
00466 
00467       cost.AddCost(ret);
00468       curh += (curh > h) ? -1 : 1;
00469       had_success = true;
00470     }
00471 
00472     if (limit <= 0) break;
00473   }
00474 
00475   delete iter;
00476   return had_success ? cost : last_error;
00477 }