tunnelbridge_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: tunnelbridge_cmd.cpp 21780 2011-01-14 13:19:23Z terkhen $ */
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 
00016 #include "stdafx.h"
00017 #include "newgrf_object.h"
00018 #include "viewport_func.h"
00019 #include "cmd_helper.h"
00020 #include "command_func.h"
00021 #include "town.h"
00022 #include "train.h"
00023 #include "ship.h"
00024 #include "roadveh.h"
00025 #include "water_map.h"
00026 #include "pathfinder/yapf/yapf_cache.h"
00027 #include "newgrf_sound.h"
00028 #include "autoslope.h"
00029 #include "tunnelbridge_map.h"
00030 #include "strings_func.h"
00031 #include "date_func.h"
00032 #include "functions.h"
00033 #include "vehicle_func.h"
00034 #include "sound_func.h"
00035 #include "tunnelbridge.h"
00036 #include "cheat_type.h"
00037 #include "elrail_func.h"
00038 #include "pbs.h"
00039 #include "company_base.h"
00040 #include "newgrf_railtype.h"
00041 #include "object_base.h"
00042 #include "water.h"
00043 
00044 #include "table/sprites.h"
00045 #include "table/strings.h"
00046 #include "table/bridge_land.h"
00047 
00048 BridgeSpec _bridge[MAX_BRIDGES];
00049 TileIndex _build_tunnel_endtile;
00050 
00051 /* Z position of the bridge sprites relative to bridge height (downwards) */
00052 static const int BRIDGE_Z_START = 3;
00053 
00055 void ResetBridges()
00056 {
00057   /* First, free sprite table data */
00058   for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
00059     if (_bridge[i].sprite_table != NULL) {
00060       for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
00061       free(_bridge[i].sprite_table);
00062     }
00063   }
00064 
00065   /* Then, wipe out current bidges */
00066   memset(&_bridge, 0, sizeof(_bridge));
00067   /* And finally, reinstall default data */
00068   memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
00069 }
00070 
00077 int CalcBridgeLenCostFactor(int length)
00078 {
00079   if (length < 2) return length;
00080 
00081   length -= 2;
00082   int sum = 2;
00083   for (int delta = 1;; delta++) {
00084     for (int count = 0; count < delta; count++) {
00085       if (length == 0) return sum;
00086       sum += delta;
00087       length--;
00088     }
00089   }
00090 }
00091 
00092 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
00093 {
00094   if (tileh == SLOPE_FLAT ||
00095       ((tileh == SLOPE_NE || tileh == SLOPE_SW) && axis == AXIS_X) ||
00096       ((tileh == SLOPE_NW || tileh == SLOPE_SE) && axis == AXIS_Y)) return FOUNDATION_NONE;
00097 
00098   return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
00099 }
00100 
00108 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
00109 {
00110   ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
00111   /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
00112   return (tileh != SLOPE_FLAT);
00113 }
00114 
00115 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
00116 {
00117   const BridgeSpec *bridge = GetBridgeSpec(index);
00118   assert(table < BRIDGE_PIECE_INVALID);
00119   if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
00120     return _bridge_sprite_table[index][table];
00121   } else {
00122     return bridge->sprite_table[table];
00123   }
00124 }
00125 
00126 
00135 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, uint *z)
00136 {
00137   Foundation f = GetBridgeFoundation(*tileh, axis);
00138   *z += ApplyFoundationToSlope(f, tileh);
00139 
00140   Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
00141   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00142 
00143   if (f == FOUNDATION_NONE) return CommandCost();
00144 
00145   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00146 }
00147 
00156 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, uint *z)
00157 {
00158   Foundation f = GetBridgeFoundation(*tileh, axis);
00159   *z += ApplyFoundationToSlope(f, tileh);
00160 
00161   Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
00162   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00163 
00164   if (f == FOUNDATION_NONE) return CommandCost();
00165 
00166   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00167 }
00168 
00175 CommandCost CheckBridgeAvailability(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
00176 {
00177   if (flags & DC_QUERY_COST) {
00178     if (bridge_len <= (_settings_game.construction.longbridges ? MAX_BRIDGE_LENGTH_LONGBRIDGES : MAX_BRIDGE_LENGTH)) return CommandCost();
00179     return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00180   }
00181 
00182   if (bridge_type >= MAX_BRIDGES) return CMD_ERROR;
00183 
00184   const BridgeSpec *b = GetBridgeSpec(bridge_type);
00185   if (b->avail_year > _cur_year) return CMD_ERROR;
00186 
00187   uint max = b->max_length;
00188   if (max >= MAX_BRIDGE_LENGTH && _settings_game.construction.longbridges) max = MAX_BRIDGE_LENGTH_LONGBRIDGES;
00189 
00190   if (b->min_length > bridge_len) return CMD_ERROR;
00191   if (bridge_len <= max) return CommandCost();
00192   return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00193 }
00194 
00207 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00208 {
00209   RailType railtype = INVALID_RAILTYPE;
00210   RoadTypes roadtypes = ROADTYPES_NONE;
00211 
00212   /* unpack parameters */
00213   BridgeType bridge_type = GB(p2, 0, 8);
00214 
00215   if (!IsValidTile(p1)) return_cmd_error(STR_ERROR_BRIDGE_THROUGH_MAP_BORDER);
00216 
00217   TransportType transport_type = Extract<TransportType, 15, 2>(p2);
00218 
00219   /* type of bridge */
00220   switch (transport_type) {
00221     case TRANSPORT_ROAD:
00222       roadtypes = Extract<RoadTypes, 8, 2>(p2);
00223       if (!HasExactlyOneBit(roadtypes) || !HasRoadTypesAvail(_current_company, roadtypes)) return CMD_ERROR;
00224       break;
00225 
00226     case TRANSPORT_RAIL:
00227       railtype = Extract<RailType, 8, 4>(p2);
00228       if (!ValParamRailtype(railtype)) return CMD_ERROR;
00229       break;
00230 
00231     case TRANSPORT_WATER:
00232       break;
00233 
00234     default:
00235       /* Airports don't have bridges. */
00236       return CMD_ERROR;
00237   }
00238   TileIndex tile_start = p1;
00239   TileIndex tile_end = end_tile;
00240 
00241   if (tile_start == tile_end) {
00242     return_cmd_error(STR_ERROR_CAN_T_START_AND_END_ON);
00243   }
00244 
00245   Axis direction;
00246   if (TileX(tile_start) == TileX(tile_end)) {
00247     direction = AXIS_Y;
00248   } else if (TileY(tile_start) == TileY(tile_end)) {
00249     direction = AXIS_X;
00250   } else {
00251     return_cmd_error(STR_ERROR_START_AND_END_MUST_BE_IN);
00252   }
00253 
00254   if (tile_end < tile_start) Swap(tile_start, tile_end);
00255 
00256   uint bridge_len = GetTunnelBridgeLength(tile_start, tile_end);
00257   if (transport_type != TRANSPORT_WATER) {
00258     /* set and test bridge length, availability */
00259     CommandCost ret = CheckBridgeAvailability(bridge_type, bridge_len, flags);
00260     if (ret.Failed()) return ret;
00261   } else {
00262     if (bridge_len > (_settings_game.construction.longbridges ? MAX_BRIDGE_LENGTH_LONGBRIDGES : MAX_BRIDGE_LENGTH)) return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00263   }
00264 
00265   uint z_start;
00266   uint z_end;
00267   Slope tileh_start = GetTileSlope(tile_start, &z_start);
00268   Slope tileh_end = GetTileSlope(tile_end, &z_end);
00269   bool pbs_reservation = false;
00270 
00271   CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
00272   CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end,   &z_end);
00273 
00274   /* Aqueducts can't be built of flat land. */
00275   if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00276   if (z_start != z_end) return_cmd_error(STR_ERROR_BRIDGEHEADS_NOT_SAME_HEIGHT);
00277 
00278   CommandCost cost(EXPENSES_CONSTRUCTION);
00279   Owner owner;
00280   if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
00281       GetOtherBridgeEnd(tile_start) == tile_end &&
00282       GetTunnelBridgeTransportType(tile_start) == transport_type) {
00283     /* Replace a current bridge. */
00284 
00285     /* If this is a railway bridge, make sure the railtypes match. */
00286     if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
00287       return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00288     }
00289 
00290     /* Do not replace town bridges with lower speed bridges. */
00291     if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
00292         GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed) {
00293       Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
00294 
00295       if (t == NULL) {
00296         return CMD_ERROR;
00297       } else {
00298         SetDParam(0, t->index);
00299         return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00300       }
00301     }
00302 
00303     /* Do not replace the bridge with the same bridge type. */
00304     if (!(flags & DC_QUERY_COST) && bridge_type == GetBridgeType(tile_start)) {
00305       return_cmd_error(STR_ERROR_ALREADY_BUILT);
00306     }
00307 
00308     /* Do not allow replacing another company's bridges. */
00309     if (!IsTileOwner(tile_start, _current_company) && !IsTileOwner(tile_start, OWNER_TOWN)) {
00310       return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
00311     }
00312 
00313     cost.AddCost((bridge_len + 1) * _price[PR_CLEAR_BRIDGE]); // The cost of clearing the current bridge.
00314     owner = GetTileOwner(tile_start);
00315 
00316     switch (transport_type) {
00317       case TRANSPORT_RAIL:
00318         /* Keep the reservation, the path stays valid. */
00319         pbs_reservation = HasTunnelBridgeReservation(tile_start);
00320         break;
00321 
00322       case TRANSPORT_ROAD:
00323         /* Do not remove road types when upgrading a bridge */
00324         roadtypes |= GetRoadTypes(tile_start);
00325         break;
00326 
00327       default: break;
00328     }
00329   } else {
00330     /* Build a new bridge. */
00331 
00332     bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
00333 
00334     /* Try and clear the start landscape */
00335     CommandCost ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00336     if (ret.Failed()) return ret;
00337     cost = ret;
00338 
00339     if (terraform_cost_north.Failed() || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00340     cost.AddCost(terraform_cost_north);
00341 
00342     /* Try and clear the end landscape */
00343     ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00344     if (ret.Failed()) return ret;
00345     cost.AddCost(ret);
00346 
00347     /* false - end tile slope check */
00348     if (terraform_cost_south.Failed() || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00349     cost.AddCost(terraform_cost_south);
00350 
00351     const TileIndex heads[] = {tile_start, tile_end};
00352     for (int i = 0; i < 2; i++) {
00353       if (MayHaveBridgeAbove(heads[i])) {
00354         if (IsBridgeAbove(heads[i])) {
00355           TileIndex north_head = GetNorthernBridgeEnd(heads[i]);
00356 
00357           if (direction == GetBridgeAxis(heads[i])) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00358 
00359           if (z_start + TILE_HEIGHT == GetBridgeHeight(north_head)) {
00360             return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00361           }
00362         }
00363       }
00364     }
00365 
00366     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00367     for (TileIndex tile = tile_start + delta; tile != tile_end; tile += delta) {
00368       if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_ERROR_BRIDGE_TOO_LOW_FOR_TERRAIN);
00369 
00370       if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00371         /* Disallow crossing bridges for the time being */
00372         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00373       }
00374 
00375       switch (GetTileType(tile)) {
00376         case MP_WATER:
00377           if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
00378           break;
00379 
00380         case MP_RAILWAY:
00381           if (!IsPlainRail(tile)) goto not_valid_below;
00382           break;
00383 
00384         case MP_ROAD:
00385           if (IsRoadDepot(tile)) goto not_valid_below;
00386           break;
00387 
00388         case MP_TUNNELBRIDGE:
00389           if (IsTunnel(tile)) break;
00390           if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
00391           if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
00392           break;
00393 
00394         case MP_OBJECT: {
00395           const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
00396           if ((spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) == 0) goto not_valid_below;
00397           if (GetTileMaxZ(tile) + spec->height * TILE_HEIGHT > z_start) goto not_valid_below;
00398           break;
00399         }
00400 
00401         case MP_CLEAR:
00402           break;
00403 
00404         default:
00405   not_valid_below:;
00406           /* try and clear the middle landscape */
00407           ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00408           if (ret.Failed()) return ret;
00409           cost.AddCost(ret);
00410           break;
00411       }
00412 
00413       if (flags & DC_EXEC) {
00414         /* We do this here because when replacing a bridge with another
00415          * type calling SetBridgeMiddle isn't needed. After all, the
00416          * tile alread has the has_bridge_above bits set. */
00417         SetBridgeMiddle(tile, direction);
00418       }
00419     }
00420 
00421     owner = _current_company;
00422   }
00423 
00424   /* do the drill? */
00425   if (flags & DC_EXEC) {
00426     DiagDirection dir = AxisToDiagDir(direction);
00427 
00428     switch (transport_type) {
00429       case TRANSPORT_RAIL:
00430         MakeRailBridgeRamp(tile_start, owner, bridge_type, dir,                 railtype);
00431         MakeRailBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), railtype);
00432         SetTunnelBridgeReservation(tile_start, pbs_reservation);
00433         SetTunnelBridgeReservation(tile_end,   pbs_reservation);
00434         break;
00435 
00436       case TRANSPORT_ROAD:
00437         MakeRoadBridgeRamp(tile_start, owner, bridge_type, dir,                 roadtypes);
00438         MakeRoadBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), roadtypes);
00439         break;
00440 
00441       case TRANSPORT_WATER:
00442         MakeAqueductBridgeRamp(tile_start, owner, dir);
00443         MakeAqueductBridgeRamp(tile_end,   owner, ReverseDiagDir(dir));
00444         break;
00445 
00446       default:
00447         NOT_REACHED();
00448     }
00449 
00450     /* Mark all tiles dirty */
00451     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00452     for (TileIndex tile = tile_start; tile <= tile_end; tile += delta) {
00453       MarkTileDirtyByTile(tile);
00454     }
00455   }
00456 
00457   if ((flags & DC_EXEC) && transport_type == TRANSPORT_RAIL) {
00458     Track track = AxisToTrack(direction);
00459     AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, _current_company);
00460     YapfNotifyTrackLayoutChange(tile_start, track);
00461   }
00462 
00463   /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
00464    * It's unnecessary to execute this command every time for every bridge. So it is done only
00465    * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
00466    */
00467   Company *c = Company::GetIfValid(_current_company);
00468   if (!(flags & DC_QUERY_COST) || (c != NULL && c->is_ai)) {
00469     bridge_len += 2; // begin and end tiles/ramps
00470 
00471     switch (transport_type) {
00472       case TRANSPORT_ROAD: cost.AddCost(bridge_len * _price[PR_BUILD_ROAD] * 2); break;
00473       case TRANSPORT_RAIL: cost.AddCost(bridge_len * RailBuildCost(railtype)); break;
00474       default: break;
00475     }
00476 
00477     if (c != NULL) bridge_len = CalcBridgeLenCostFactor(bridge_len);
00478 
00479     if (transport_type != TRANSPORT_WATER) {
00480       cost.AddCost((int64)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8);
00481     } else {
00482       /* Aqueducts use a separate base cost. */
00483       cost.AddCost((int64)bridge_len * _price[PR_BUILD_AQUEDUCT]);
00484     }
00485 
00486   }
00487 
00488   return cost;
00489 }
00490 
00491 
00502 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00503 {
00504   TransportType transport_type = Extract<TransportType, 8, 2>(p1);
00505 
00506   RailType railtype = INVALID_RAILTYPE;
00507   RoadTypes rts = ROADTYPES_NONE;
00508   _build_tunnel_endtile = 0;
00509   switch (transport_type) {
00510     case TRANSPORT_RAIL:
00511       railtype = Extract<RailType, 0, 4>(p1);
00512       if (!ValParamRailtype(railtype)) return CMD_ERROR;
00513       break;
00514 
00515     case TRANSPORT_ROAD:
00516       rts = Extract<RoadTypes, 0, 2>(p1);
00517       if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
00518       break;
00519 
00520     default: return CMD_ERROR;
00521   }
00522 
00523   uint start_z;
00524   uint end_z;
00525   Slope start_tileh = GetTileSlope(start_tile, &start_z);
00526   DiagDirection direction = GetInclinedSlopeDirection(start_tileh);
00527   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL);
00528 
00529   if (HasTileWaterGround(start_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00530 
00531   CommandCost ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00532   if (ret.Failed()) return ret;
00533 
00534   /* XXX - do NOT change 'ret' in the loop, as it is used as the price
00535    * for the clearing of the entrance of the tunnel. Assigning it to
00536    * cost before the loop will yield different costs depending on start-
00537    * position, because of increased-cost-by-length: 'cost += cost >> 3' */
00538 
00539   TileIndexDiff delta = TileOffsByDiagDir(direction);
00540   DiagDirection tunnel_in_way_dir;
00541   if (DiagDirToAxis(direction) == AXIS_Y) {
00542     tunnel_in_way_dir = (TileX(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SW : DIAGDIR_NE;
00543   } else {
00544     tunnel_in_way_dir = (TileY(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SE : DIAGDIR_NW;
00545   }
00546 
00547   TileIndex end_tile = start_tile;
00548 
00549   /* Tile shift coeficient. Will decrease for very long tunnels to avoid exponential growth of price*/
00550   int tiles_coef = 3;
00551   /* Number of tiles from start of tunnel */
00552   int tiles = 0;
00553   /* Number of tiles at which the cost increase coefficient per tile is halved */
00554   int tiles_bump = 25;
00555 
00556   CommandCost cost(EXPENSES_CONSTRUCTION);
00557   Slope end_tileh;
00558   for (;;) {
00559     end_tile += delta;
00560     if (!IsValidTile(end_tile)) return_cmd_error(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER);
00561     end_tileh = GetTileSlope(end_tile, &end_z);
00562 
00563     if (start_z == end_z) break;
00564 
00565     if (!_cheats.crossing_tunnels.value && IsTunnelInWayDir(end_tile, start_z, tunnel_in_way_dir)) {
00566       return_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY);
00567     }
00568 
00569     tiles++;
00570     if (tiles == tiles_bump) {
00571       tiles_coef++;
00572       tiles_bump *= 2;
00573     }
00574 
00575     cost.AddCost(_price[PR_BUILD_TUNNEL]);
00576     cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
00577   }
00578 
00579   /* Add the cost of the entrance */
00580   cost.AddCost(_price[PR_BUILD_TUNNEL]);
00581   cost.AddCost(ret);
00582 
00583   /* if the command fails from here on we want the end tile to be highlighted */
00584   _build_tunnel_endtile = end_tile;
00585 
00586   if (HasTileWaterGround(end_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00587 
00588   /* Clear the tile in any case */
00589   ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00590   if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
00591   cost.AddCost(ret);
00592 
00593   /* slope of end tile must be complementary to the slope of the start tile */
00594   if (end_tileh != ComplementSlope(start_tileh)) {
00595     /* Mark the tile as already cleared for the terraform command.
00596      * Do this for all tiles (like trees), not only objects. */
00597     ClearedObjectArea *coa = FindClearedObject(end_tile);
00598     if (coa == NULL) {
00599       coa = _cleared_object_areas.Append();
00600       coa->first_tile = end_tile;
00601       coa->area = TileArea(end_tile, 1, 1);
00602     }
00603 
00604     /* Hide the tile from the terraforming command */
00605     TileIndex old_first_tile = coa->first_tile;
00606     coa->first_tile = INVALID_TILE;
00607     ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
00608     coa->first_tile = old_first_tile;
00609     if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
00610     cost.AddCost(ret);
00611   }
00612   cost.AddCost(_price[PR_BUILD_TUNNEL]);
00613 
00614   /* Pay for the rail/road in the tunnel including entrances */
00615   switch (transport_type) {
00616     case TRANSPORT_ROAD: cost.AddCost((tiles + 2) * _price[PR_BUILD_ROAD] * 2); break;
00617     case TRANSPORT_RAIL: cost.AddCost((tiles + 2) * RailBuildCost(railtype)); break;
00618     default: break;
00619   }
00620 
00621   if (flags & DC_EXEC) {
00622     if (transport_type == TRANSPORT_RAIL) {
00623       MakeRailTunnel(start_tile, _current_company, direction,                 railtype);
00624       MakeRailTunnel(end_tile,   _current_company, ReverseDiagDir(direction), railtype);
00625       AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, _current_company);
00626       YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
00627     } else {
00628       MakeRoadTunnel(start_tile, _current_company, direction,                 rts);
00629       MakeRoadTunnel(end_tile,   _current_company, ReverseDiagDir(direction), rts);
00630     }
00631   }
00632 
00633   return cost;
00634 }
00635 
00636 
00642 static inline CommandCost CheckAllowRemoveTunnelBridge(TileIndex tile)
00643 {
00644   /* Floods can remove anything as well as the scenario editor */
00645   if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return CommandCost();
00646 
00647   switch (GetTunnelBridgeTransportType(tile)) {
00648     case TRANSPORT_ROAD: {
00649       RoadTypes rts = GetRoadTypes(tile);
00650       Owner road_owner = _current_company;
00651       Owner tram_owner = _current_company;
00652 
00653       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
00654       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
00655 
00656       /* We can remove unowned road and if the town allows it */
00657       if (road_owner == OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) {
00658         return CheckTileOwnership(tile);
00659       }
00660       if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
00661       if (tram_owner == OWNER_NONE) tram_owner = _current_company;
00662 
00663       CommandCost ret = CheckOwnership(road_owner, tile);
00664       if (ret.Succeeded()) ret = CheckOwnership(tram_owner, tile);
00665       return ret;
00666     }
00667 
00668     case TRANSPORT_RAIL:
00669     case TRANSPORT_WATER:
00670       return CheckOwnership(GetTileOwner(tile));
00671 
00672     default: NOT_REACHED();
00673   }
00674 }
00675 
00682 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
00683 {
00684   CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
00685   if (ret.Failed()) return ret;
00686 
00687   TileIndex endtile = GetOtherTunnelEnd(tile);
00688 
00689   ret = TunnelBridgeIsFree(tile, endtile);
00690   if (ret.Failed()) return ret;
00691 
00692   _build_tunnel_endtile = endtile;
00693 
00694   Town *t = NULL;
00695   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00696     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00697 
00698     /* Check if you are allowed to remove the tunnel owned by a town
00699      * Removal depends on difficulty settings */
00700     CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
00701     if (ret.Failed()) return ret;
00702   }
00703 
00704   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00705    * you have a "Poor" (0) town rating */
00706   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00707     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00708   }
00709 
00710   if (flags & DC_EXEC) {
00711     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
00712       /* We first need to request values before calling DoClearSquare */
00713       DiagDirection dir = GetTunnelBridgeDirection(tile);
00714       Track track = DiagDirToDiagTrack(dir);
00715       Owner owner = GetTileOwner(tile);
00716 
00717       Train *v = NULL;
00718       if (HasTunnelBridgeReservation(tile)) {
00719         v = GetTrainForReservation(tile, track);
00720         if (v != NULL) FreeTrainTrackReservation(v);
00721       }
00722 
00723       DoClearSquare(tile);
00724       DoClearSquare(endtile);
00725 
00726       /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
00727       AddSideToSignalBuffer(tile,    ReverseDiagDir(dir), owner);
00728       AddSideToSignalBuffer(endtile, dir,                 owner);
00729 
00730       YapfNotifyTrackLayoutChange(tile,    track);
00731       YapfNotifyTrackLayoutChange(endtile, track);
00732 
00733       if (v != NULL) TryPathReserve(v);
00734     } else {
00735       DoClearSquare(tile);
00736       DoClearSquare(endtile);
00737     }
00738   }
00739   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_TUNNEL] * (GetTunnelBridgeLength(tile, endtile) + 2));
00740 }
00741 
00742 
00749 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
00750 {
00751   CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
00752   if (ret.Failed()) return ret;
00753 
00754   TileIndex endtile = GetOtherBridgeEnd(tile);
00755 
00756   ret = TunnelBridgeIsFree(tile, endtile);
00757   if (ret.Failed()) return ret;
00758 
00759   DiagDirection direction = GetTunnelBridgeDirection(tile);
00760   TileIndexDiff delta = TileOffsByDiagDir(direction);
00761 
00762   Town *t = NULL;
00763   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00764     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00765 
00766     /* Check if you are allowed to remove the bridge owned by a town
00767      * Removal depends on difficulty settings */
00768     CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
00769     if (ret.Failed()) return ret;
00770   }
00771 
00772   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00773    * you have a "Poor" (0) town rating */
00774   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00775     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00776   }
00777 
00778   Money base_cost = (GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) ? _price[PR_CLEAR_BRIDGE] : _price[PR_CLEAR_AQUEDUCT];
00779 
00780   if (flags & DC_EXEC) {
00781     /* read this value before actual removal of bridge */
00782     bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
00783     Owner owner = GetTileOwner(tile);
00784     uint height = GetBridgeHeight(tile);
00785     Train *v = NULL;
00786 
00787     if (rail && HasTunnelBridgeReservation(tile)) {
00788       v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
00789       if (v != NULL) FreeTrainTrackReservation(v);
00790     }
00791 
00792     DoClearSquare(tile);
00793     DoClearSquare(endtile);
00794     for (TileIndex c = tile + delta; c != endtile; c += delta) {
00795       /* do not let trees appear from 'nowhere' after removing bridge */
00796       if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
00797         uint minz = GetTileMaxZ(c) + 3 * TILE_HEIGHT;
00798         if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
00799       }
00800       ClearBridgeMiddle(c);
00801       MarkTileDirtyByTile(c);
00802     }
00803 
00804     if (rail) {
00805       /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
00806       AddSideToSignalBuffer(tile,    ReverseDiagDir(direction), owner);
00807       AddSideToSignalBuffer(endtile, direction,                 owner);
00808 
00809       Track track = DiagDirToDiagTrack(direction);
00810       YapfNotifyTrackLayoutChange(tile,    track);
00811       YapfNotifyTrackLayoutChange(endtile, track);
00812 
00813       if (v != NULL) TryPathReserve(v, true);
00814     }
00815   }
00816 
00817   return CommandCost(EXPENSES_CONSTRUCTION, (GetTunnelBridgeLength(tile, endtile) + 2) * base_cost);
00818 }
00819 
00826 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
00827 {
00828   if (IsTunnel(tile)) {
00829     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST);
00830     return DoClearTunnel(tile, flags);
00831   } else { // IsBridge(tile)
00832     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00833     return DoClearBridge(tile, flags);
00834   }
00835 }
00836 
00847 static inline void DrawPillar(const PalSpriteID *psid, int x, int y, int z, int w, int h, const SubSprite *subsprite)
00848 {
00849   static const int PILLAR_Z_OFFSET = TILE_HEIGHT - BRIDGE_Z_START; 
00850   AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, w, h, BB_HEIGHT_UNDER_BRIDGE - PILLAR_Z_OFFSET, z, IsTransparencySet(TO_BRIDGES), 0, 0, -PILLAR_Z_OFFSET, subsprite);
00851 }
00852 
00864 static int DrawPillarColumn(int z_bottom, int z_top, const PalSpriteID *psid, int x, int y, int w, int h)
00865 {
00866   int cur_z;
00867   for (cur_z = z_top; cur_z >= z_bottom; cur_z -= TILE_HEIGHT) {
00868     DrawPillar(psid, x, y, cur_z, w, h, NULL);
00869   }
00870   return cur_z;
00871 }
00872 
00884 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
00885 {
00886   static const int bounding_box_size[2]  = {16, 2}; 
00887   static const int back_pillar_offset[2] = { 0, 9}; 
00888 
00889   static const int INF = 1000; 
00890   static const SubSprite half_pillar_sub_sprite[2][2] = {
00891     { {  -14, -INF, INF, INF }, { -INF, -INF, -15, INF } }, // X axis, north and south
00892     { { -INF, -INF,  15, INF }, {   16, -INF, INF, INF } }, // Y axis, north and south
00893   };
00894 
00895   if (psid->sprite == 0) return;
00896 
00897   /* Determine ground height under pillars */
00898   DiagDirection south_dir = AxisToDiagDir(axis);
00899   int z_front_north = ti->z;
00900   int z_back_north = ti->z;
00901   int z_front_south = ti->z;
00902   int z_back_south = ti->z;
00903   GetSlopeZOnEdge(ti->tileh, south_dir, &z_front_south, &z_back_south);
00904   GetSlopeZOnEdge(ti->tileh, ReverseDiagDir(south_dir), &z_front_north, &z_back_north);
00905 
00906   /* Shared height of pillars */
00907   int z_front = max(z_front_north, z_front_south);
00908   int z_back = max(z_back_north, z_back_south);
00909 
00910   /* x and y size of bounding-box of pillars */
00911   int w = bounding_box_size[axis];
00912   int h = bounding_box_size[OtherAxis(axis)];
00913   /* sprite position of back facing pillar */
00914   int x_back = x - back_pillar_offset[axis];
00915   int y_back = y - back_pillar_offset[OtherAxis(axis)];
00916 
00917   /* Draw front pillars */
00918   int bottom_z = DrawPillarColumn(z_front, z_bridge, psid, x, y, w, h);
00919   if (z_front_north < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
00920   if (z_front_south < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
00921 
00922   /* Draw back pillars, skip top two parts, which are hidden by the bridge */
00923   int z_bridge_back = z_bridge - 2 * (int)TILE_HEIGHT;
00924   if (drawfarpillar && (z_back_north <= z_bridge_back || z_back_south <= z_bridge_back)) {
00925     bottom_z = DrawPillarColumn(z_back, z_bridge_back, psid, x_back, y_back, w, h);
00926     if (z_back_north < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
00927     if (z_back_south < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
00928   }
00929 }
00930 
00940 static void DrawBridgeTramBits(int x, int y, byte z, int offset, bool overlay, bool head)
00941 {
00942   static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
00943   static const SpriteID back_offsets[6]    =   {  95,  96,  99, 102, 100, 101 };
00944   static const SpriteID front_offsets[6]   =   {  97,  98, 103, 106, 104, 105 };
00945 
00946   static const uint size_x[6] = {  1, 16, 16,  1, 16,  1 };
00947   static const uint size_y[6] = { 16,  1,  1, 16,  1, 16 };
00948   static const uint front_bb_offset_x[6] = { 15,  0,  0, 15,  0, 15 };
00949   static const uint front_bb_offset_y[6] = {  0, 15, 15,  0, 15,  0 };
00950 
00951   /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
00952    * The bounding boxes here are the same as for bridge front/roof */
00953   if (head || !IsInvisibilitySet(TO_BRIDGES)) {
00954     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
00955       x, y, size_x[offset], size_y[offset], 0x28, z,
00956       !head && IsTransparencySet(TO_BRIDGES));
00957   }
00958 
00959   /* Do not draw catenary if it is set invisible */
00960   if (!IsInvisibilitySet(TO_CATENARY)) {
00961     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
00962       x, y, size_x[offset], size_y[offset], 0x28, z,
00963       IsTransparencySet(TO_CATENARY));
00964   }
00965 
00966   /* Start a new SpriteCombine for the front part */
00967   EndSpriteCombine();
00968   StartSpriteCombine();
00969 
00970   /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
00971   if (!IsInvisibilitySet(TO_CATENARY)) {
00972     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
00973       x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
00974       IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
00975   }
00976 }
00977 
00991 static void DrawTile_TunnelBridge(TileInfo *ti)
00992 {
00993   TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
00994   DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
00995 
00996   if (IsTunnel(ti->tile)) {
00997     /* Front view of tunnel bounding boxes:
00998      *
00999      *   122223  <- BB_Z_SEPARATOR
01000      *   1    3
01001      *   1    3                1,3 = empty helper BB
01002      *   1    3                  2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
01003      *
01004      */
01005 
01006     static const int _tunnel_BB[4][12] = {
01007       /*  tunnnel-roof  |  Z-separator  | tram-catenary
01008        * w  h  bb_x bb_y| x   y   w   h |bb_x bb_y w h */
01009       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // NE
01010       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // SE
01011       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // SW
01012       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // NW
01013     };
01014     const int *BB_data = _tunnel_BB[tunnelbridge_direction];
01015 
01016     bool catenary = false;
01017 
01018     SpriteID image;
01019     if (transport_type == TRANSPORT_RAIL) {
01020       image = GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.tunnel;
01021     } else {
01022       image = SPR_TUNNEL_ENTRY_REAR_ROAD;
01023     }
01024 
01025     if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += 32;
01026 
01027     image += tunnelbridge_direction * 2;
01028     DrawGroundSprite(image, PAL_NONE);
01029 
01030     /* PBS debugging, draw reserved tracks darker */
01031     if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && (transport_type == TRANSPORT_RAIL && HasTunnelBridgeReservation(ti->tile))) {
01032       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01033       DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
01034     }
01035 
01036     if (transport_type == TRANSPORT_ROAD) {
01037       RoadTypes rts = GetRoadTypes(ti->tile);
01038 
01039       if (HasBit(rts, ROADTYPE_TRAM)) {
01040         static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, {  5, 76, 77,  4 } };
01041 
01042         DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
01043 
01044         /* Do not draw wires if they are invisible */
01045         if (!IsInvisibilitySet(TO_CATENARY)) {
01046           catenary = true;
01047           StartSpriteCombine();
01048           AddSortableSpriteToDraw(SPR_TRAMWAY_TUNNEL_WIRES + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, BB_data[10], BB_data[11], TILE_HEIGHT, ti->z, IsTransparencySet(TO_CATENARY), BB_data[8], BB_data[9], BB_Z_SEPARATOR);
01049         }
01050       }
01051     } else {
01052       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01053       if (rti->UsesOverlay()) {
01054         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL);
01055         if (surface != 0) DrawGroundSprite(surface + tunnelbridge_direction, PAL_NONE);
01056       }
01057 
01058       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01059         /* Maybe draw pylons on the entry side */
01060         DrawCatenary(ti);
01061 
01062         catenary = true;
01063         StartSpriteCombine();
01064         /* Draw wire above the ramp */
01065         DrawCatenaryOnTunnel(ti);
01066       }
01067     }
01068 
01069     AddSortableSpriteToDraw(image + 1, PAL_NONE, ti->x + TILE_SIZE - 1, ti->y + TILE_SIZE - 1, BB_data[0], BB_data[1], TILE_HEIGHT, ti->z, false, BB_data[2], BB_data[3], BB_Z_SEPARATOR);
01070 
01071     if (catenary) EndSpriteCombine();
01072 
01073     /* Add helper BB for sprite sorting that separates the tunnel from things beside of it. */
01074     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x,              ti->y,              BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
01075     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x + BB_data[4], ti->y + BB_data[5], BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
01076 
01077     DrawBridgeMiddle(ti);
01078   } else { // IsBridge(ti->tile)
01079     const PalSpriteID *psid;
01080     int base_offset;
01081     bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
01082 
01083     if (transport_type == TRANSPORT_RAIL) {
01084       base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
01085       assert(base_offset != 8); // This one is used for roads
01086     } else {
01087       base_offset = 8;
01088     }
01089 
01090     /* as the lower 3 bits are used for other stuff, make sure they are clear */
01091     assert( (base_offset & 0x07) == 0x00);
01092 
01093     DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
01094 
01095     /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
01096     base_offset += (6 - tunnelbridge_direction) % 4;
01097 
01098     if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
01099 
01100     /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
01101     if (transport_type != TRANSPORT_WATER) {
01102       psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
01103     } else {
01104       psid = _aqueduct_sprites + base_offset;
01105     }
01106 
01107     if (!ice) {
01108       TileIndex next = ti->tile + TileOffsByDiagDir(tunnelbridge_direction);
01109       if (ti->tileh != SLOPE_FLAT && ti->z == 0 && HasTileWaterClass(next) && GetWaterClass(next) == WATER_CLASS_SEA) {
01110         DrawShoreTile(ti->tileh);
01111       } else {
01112         DrawClearLandTile(ti, 3);
01113       }
01114     } else {
01115       DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
01116     }
01117 
01118     /* draw ramp */
01119 
01120     /* Draw Trambits and PBS Reservation as SpriteCombine */
01121     if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
01122 
01123     /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
01124      * it doesn't disappear behind it
01125      */
01126     /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
01127     AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
01128 
01129     if (transport_type == TRANSPORT_ROAD) {
01130       RoadTypes rts = GetRoadTypes(ti->tile);
01131 
01132       if (HasBit(rts, ROADTYPE_TRAM)) {
01133         uint offset = tunnelbridge_direction;
01134         uint z = ti->z;
01135         if (ti->tileh != SLOPE_FLAT) {
01136           offset = (offset + 1) & 1;
01137           z += TILE_HEIGHT;
01138         } else {
01139           offset += 2;
01140         }
01141         /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01142         DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
01143       }
01144       EndSpriteCombine();
01145     } else if (transport_type == TRANSPORT_RAIL) {
01146       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01147       if (rti->UsesOverlay()) {
01148         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
01149         if (surface != 0) {
01150           if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
01151             AddSortableSpriteToDraw(surface + ((DiagDirToAxis(tunnelbridge_direction) == AXIS_X) ? RTBO_X : RTBO_Y), PAL_NONE, ti->x, ti->y, 16, 16, 0, ti->z + 8);
01152           } else {
01153             AddSortableSpriteToDraw(surface + RTBO_SLOPE + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, 16, 16, 8, ti->z);
01154           }
01155         }
01156         /* Don't fallback to non-overlay sprite -- the spec states that
01157          * if an overlay is present then the bridge surface must be
01158          * present. */
01159       } else if (_game_mode != GM_MENU &&_settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
01160         if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
01161           AddSortableSpriteToDraw(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH, ti->x, ti->y, 16, 16, 0, ti->z + 8);
01162         } else {
01163           AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
01164         }
01165       }
01166       EndSpriteCombine();
01167       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01168         DrawCatenary(ti);
01169       }
01170     }
01171 
01172     DrawBridgeMiddle(ti);
01173   }
01174 }
01175 
01176 
01195 static BridgePieces CalcBridgePiece(uint north, uint south)
01196 {
01197   if (north == 1) {
01198     return BRIDGE_PIECE_NORTH;
01199   } else if (south == 1) {
01200     return BRIDGE_PIECE_SOUTH;
01201   } else if (north < south) {
01202     return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
01203   } else if (north > south) {
01204     return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
01205   } else {
01206     return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
01207   }
01208 }
01209 
01210 
01211 void DrawBridgeMiddle(const TileInfo *ti)
01212 {
01213   /* Sectional view of bridge bounding boxes:
01214    *
01215    *  1           2                                1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
01216    *  1           2                                  3 = empty helper BB
01217    *  1     7     2                                4,5 = pillars under higher bridges
01218    *  1 6 88888 6 2                                  6 = elrail-pylons
01219    *  1 6 88888 6 2                                  7 = elrail-wire
01220    *  1 6 88888 6 2  <- TILE_HEIGHT                  8 = rail-vehicle on bridge
01221    *  3333333333333  <- BB_Z_SEPARATOR
01222    *                 <- unused
01223    *    4       5    <- BB_HEIGHT_UNDER_BRIDGE
01224    *    4       5
01225    *    4       5
01226    *
01227    */
01228 
01229   if (!IsBridgeAbove(ti->tile)) return;
01230 
01231   TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
01232   TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
01233   TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
01234 
01235   Axis axis = GetBridgeAxis(ti->tile);
01236   BridgePieces piece = CalcBridgePiece(
01237     GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
01238     GetTunnelBridgeLength(ti->tile, rampsouth) + 1
01239   );
01240 
01241   const PalSpriteID *psid;
01242   bool drawfarpillar;
01243   if (transport_type != TRANSPORT_WATER) {
01244     BridgeType type =  GetBridgeType(rampsouth);
01245     drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
01246 
01247     uint base_offset;
01248     if (transport_type == TRANSPORT_RAIL) {
01249       base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
01250     } else {
01251       base_offset = 8;
01252     }
01253 
01254     psid = base_offset + GetBridgeSpriteTable(type, piece);
01255   } else {
01256     drawfarpillar = true;
01257     psid = _aqueduct_sprites;
01258   }
01259 
01260   if (axis != AXIS_X) psid += 4;
01261 
01262   int x = ti->x;
01263   int y = ti->y;
01264   uint bridge_z = GetBridgeHeight(rampsouth);
01265   uint z = bridge_z - BRIDGE_Z_START;
01266 
01267   /* Add a bounding box that separates the bridge from things below it. */
01268   AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
01269 
01270   /* Draw Trambits as SpriteCombine */
01271   if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
01272 
01273   /* Draw floor and far part of bridge*/
01274   if (!IsInvisibilitySet(TO_BRIDGES)) {
01275     if (axis == AXIS_X) {
01276       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01277     } else {
01278       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01279     }
01280   }
01281 
01282   psid++;
01283 
01284   if (transport_type == TRANSPORT_ROAD) {
01285     RoadTypes rts = GetRoadTypes(rampsouth);
01286 
01287     if (HasBit(rts, ROADTYPE_TRAM)) {
01288       /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01289       DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
01290     } else {
01291       EndSpriteCombine();
01292       StartSpriteCombine();
01293     }
01294   } else if (transport_type == TRANSPORT_RAIL) {
01295     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(rampsouth));
01296     if (rti->UsesOverlay()) {
01297       SpriteID surface = GetCustomRailSprite(rti, rampsouth, RTSG_BRIDGE, TCX_ON_BRIDGE);
01298       if (surface != 0) {
01299         AddSortableSpriteToDraw(surface + axis, PAL_NONE, x, y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
01300       }
01301     }
01302     EndSpriteCombine();
01303 
01304     if (HasCatenaryDrawn(GetRailType(rampsouth))) {
01305       DrawCatenaryOnBridge(ti);
01306     }
01307   }
01308 
01309   /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
01310   if (!IsInvisibilitySet(TO_BRIDGES)) {
01311     if (axis == AXIS_X) {
01312       y += 12;
01313       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
01314     } else {
01315       x += 12;
01316       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
01317     }
01318   }
01319 
01320   /* Draw TramFront as SpriteCombine */
01321   if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
01322 
01323   /* Do not draw anything more if bridges are invisible */
01324   if (IsInvisibilitySet(TO_BRIDGES)) return;
01325 
01326   psid++;
01327   if (ti->z + 5 == z) {
01328     /* draw poles below for small bridges */
01329     if (psid->sprite != 0) {
01330       SpriteID image = psid->sprite;
01331       SpriteID pal   = psid->pal;
01332       if (IsTransparencySet(TO_BRIDGES)) {
01333         SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
01334         pal = PALETTE_TO_TRANSPARENT;
01335       }
01336 
01337       DrawGroundSpriteAt(image, pal, x - ti->x, y - ti->y, z - ti->z);
01338     }
01339   } else if (_settings_client.gui.bridge_pillars) {
01340     /* draw pillars below for high bridges */
01341     DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
01342   }
01343 }
01344 
01345 
01346 static uint GetSlopeZ_TunnelBridge(TileIndex tile, uint x, uint y)
01347 {
01348   uint z;
01349   Slope tileh = GetTileSlope(tile, &z);
01350 
01351   x &= 0xF;
01352   y &= 0xF;
01353 
01354   if (IsTunnel(tile)) {
01355     uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
01356 
01357     /* In the tunnel entrance? */
01358     if (5 <= pos && pos <= 10) return z;
01359   } else { // IsBridge(tile)
01360     DiagDirection dir = GetTunnelBridgeDirection(tile);
01361     uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
01362 
01363     z += ApplyFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
01364 
01365     /* On the bridge ramp? */
01366     if (5 <= pos && pos <= 10) {
01367       uint delta;
01368 
01369       if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
01370 
01371       switch (dir) {
01372         default: NOT_REACHED();
01373         case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
01374         case DIAGDIR_SE: delta = y / 2; break;
01375         case DIAGDIR_SW: delta = x / 2; break;
01376         case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
01377       }
01378       return z + 1 + delta;
01379     }
01380   }
01381 
01382   return z + GetPartialZ(x, y, tileh);
01383 }
01384 
01385 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
01386 {
01387   return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
01388 }
01389 
01390 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
01391 {
01392   TransportType tt = GetTunnelBridgeTransportType(tile);
01393 
01394   if (IsTunnel(tile)) {
01395     td->str = (tt == TRANSPORT_RAIL) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD : STR_LAI_TUNNEL_DESCRIPTION_ROAD;
01396   } else { // IsBridge(tile)
01397     td->str = (tt == TRANSPORT_WATER) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
01398   }
01399   td->owner[0] = GetTileOwner(tile);
01400 
01401   Owner road_owner = INVALID_OWNER;
01402   Owner tram_owner = INVALID_OWNER;
01403   RoadTypes rts = GetRoadTypes(tile);
01404   if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01405   if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01406 
01407   /* Is there a mix of owners? */
01408   if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
01409       (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
01410     uint i = 1;
01411     if (road_owner != INVALID_OWNER) {
01412       td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
01413       td->owner[i] = road_owner;
01414       i++;
01415     }
01416     if (tram_owner != INVALID_OWNER) {
01417       td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
01418       td->owner[i] = tram_owner;
01419     }
01420   }
01421 
01422   if (tt == TRANSPORT_RAIL) {
01423     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
01424     td->rail_speed = rti->max_speed;
01425 
01426     if (!IsTunnel(tile)) {
01427       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01428       if (td->rail_speed == 0 || spd < td->rail_speed) {
01429         td->rail_speed = spd;
01430       }
01431     }
01432   }
01433 }
01434 
01435 
01436 static void TileLoop_TunnelBridge(TileIndex tile)
01437 {
01438   bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
01439   switch (_settings_game.game_creation.landscape) {
01440     case LT_ARCTIC: {
01441       /* As long as we do not have a snow density, we want to use the density
01442        * from the entry endge. For tunnels this is the lowest point for bridges the highest point.
01443        * (Independent of foundations) */
01444       uint z = IsBridge(tile) ? GetTileMaxZ(tile) : GetTileZ(tile);
01445       if (snow_or_desert != (z > GetSnowLine())) {
01446         SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
01447         MarkTileDirtyByTile(tile);
01448       }
01449       break;
01450     }
01451 
01452     case LT_TROPIC:
01453       if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
01454         SetTunnelBridgeSnowOrDesert(tile, true);
01455         MarkTileDirtyByTile(tile);
01456       }
01457       break;
01458 
01459     default:
01460       break;
01461   }
01462 }
01463 
01464 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
01465 {
01466   TransportType transport_type = GetTunnelBridgeTransportType(tile);
01467   if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
01468 
01469   DiagDirection dir = GetTunnelBridgeDirection(tile);
01470   if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
01471   return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
01472 }
01473 
01474 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
01475 {
01476   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01477     /* Update all roadtypes, no matter if they are present */
01478     if (GetRoadOwner(tile, rt) == old_owner) {
01479       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
01480     }
01481   }
01482 
01483   if (!IsTileOwner(tile, old_owner)) return;
01484 
01485   if (new_owner != INVALID_OWNER) {
01486     SetTileOwner(tile, new_owner);
01487   } else {
01488     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
01489       /* Since all of our vehicles have been removed, it is safe to remove the rail
01490        * bridge / tunnel. */
01491       CommandCost ret = DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
01492       assert(ret.Succeeded());
01493     } else {
01494       /* In any other case, we can safely reassign the ownership to OWNER_NONE. */
01495       SetTileOwner(tile, OWNER_NONE);
01496     }
01497   }
01498 }
01499 
01505 static const byte TUNNEL_SOUND_FRAME = 1;
01506 
01515 extern const byte _tunnel_visibility_frame[DIAGDIR_END] = {12, 8, 8, 12};
01516 
01517 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
01518 {
01519   int z = GetSlopeZ(x, y) - v->z_pos;
01520 
01521   if (abs(z) > 2) return VETSB_CANNOT_ENTER;
01522   /* Direction into the wormhole */
01523   const DiagDirection dir = GetTunnelBridgeDirection(tile);
01524   /* Direction of the vehicle */
01525   const DiagDirection vdir = DirToDiagDir(v->direction);
01526   /* New position of the vehicle on the tile */
01527   byte pos = (DiagDirToAxis(vdir) == AXIS_X ? x : y) & TILE_UNIT_MASK;
01528   /* Number of units moved by the vehicle since entering the tile */
01529   byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
01530 
01531   if (IsTunnel(tile)) {
01532     if (v->type == VEH_TRAIN) {
01533       Train *t = Train::From(v);
01534 
01535       if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
01536         if (t->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
01537           if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
01538             SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
01539           }
01540           return VETSB_CONTINUE;
01541         }
01542         if (frame == _tunnel_visibility_frame[dir]) {
01543           t->tile = tile;
01544           t->track = TRACK_BIT_WORMHOLE;
01545           t->vehstatus |= VS_HIDDEN;
01546           return VETSB_ENTERED_WORMHOLE;
01547         }
01548       }
01549 
01550       if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
01551         /* We're at the tunnel exit ?? */
01552         t->tile = tile;
01553         t->track = DiagDirToDiagTrackBits(vdir);
01554         assert(t->track);
01555         t->vehstatus &= ~VS_HIDDEN;
01556         return VETSB_ENTERED_WORMHOLE;
01557       }
01558     } else if (v->type == VEH_ROAD) {
01559       RoadVehicle *rv = RoadVehicle::From(v);
01560 
01561       /* Enter tunnel? */
01562       if (rv->state != RVSB_WORMHOLE && dir == vdir) {
01563         if (frame == _tunnel_visibility_frame[dir]) {
01564           /* Frame should be equal to the next frame number in the RV's movement */
01565           assert(frame == rv->frame + 1);
01566           rv->tile = tile;
01567           rv->state = RVSB_WORMHOLE;
01568           rv->vehstatus |= VS_HIDDEN;
01569           return VETSB_ENTERED_WORMHOLE;
01570         } else {
01571           return VETSB_CONTINUE;
01572         }
01573       }
01574 
01575       /* We're at the tunnel exit ?? */
01576       if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
01577         rv->tile = tile;
01578         rv->state = DiagDirToDiagTrackdir(vdir);
01579         rv->frame = frame;
01580         rv->vehstatus &= ~VS_HIDDEN;
01581         return VETSB_ENTERED_WORMHOLE;
01582       }
01583     }
01584   } else { // IsBridge(tile)
01585     if (v->type != VEH_SHIP) {
01586       /* modify speed of vehicle */
01587       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01588 
01589       if (v->type == VEH_ROAD) spd *= 2;
01590       Vehicle *first = v->First();
01591       first->cur_speed = min(first->cur_speed, spd);
01592     }
01593 
01594     if (vdir == dir) {
01595       /* Vehicle enters bridge at the last frame inside this tile. */
01596       if (frame != TILE_SIZE - 1) return VETSB_CONTINUE;
01597       switch (v->type) {
01598         case VEH_TRAIN: {
01599           Train *t = Train::From(v);
01600           t->track = TRACK_BIT_WORMHOLE;
01601           ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
01602           ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
01603           break;
01604         }
01605 
01606         case VEH_ROAD: {
01607           RoadVehicle *rv = RoadVehicle::From(v);
01608           rv->state = RVSB_WORMHOLE;
01609           /* There are no slopes inside bridges / tunnels. */
01610           ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
01611           ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
01612           break;
01613         }
01614 
01615         case VEH_SHIP:
01616           Ship::From(v)->state = TRACK_BIT_WORMHOLE;
01617           break;
01618 
01619         default: NOT_REACHED();
01620       }
01621       return VETSB_ENTERED_WORMHOLE;
01622     } else if (vdir == ReverseDiagDir(dir)) {
01623       v->tile = tile;
01624       switch (v->type) {
01625         case VEH_TRAIN: {
01626           Train *t = Train::From(v);
01627           if (t->track == TRACK_BIT_WORMHOLE) {
01628             t->track = DiagDirToDiagTrackBits(vdir);
01629             return VETSB_ENTERED_WORMHOLE;
01630           }
01631           break;
01632         }
01633 
01634         case VEH_ROAD: {
01635           RoadVehicle *rv = RoadVehicle::From(v);
01636           if (rv->state == RVSB_WORMHOLE) {
01637             rv->state = DiagDirToDiagTrackdir(vdir);
01638             rv->frame = 0;
01639             return VETSB_ENTERED_WORMHOLE;
01640           }
01641           break;
01642         }
01643 
01644         case VEH_SHIP: {
01645           Ship *ship = Ship::From(v);
01646           if (ship->state == TRACK_BIT_WORMHOLE) {
01647             ship->state = DiagDirToDiagTrackBits(vdir);
01648             return VETSB_ENTERED_WORMHOLE;
01649           }
01650           break;
01651         }
01652 
01653         default: NOT_REACHED();
01654       }
01655     }
01656   }
01657   return VETSB_CONTINUE;
01658 }
01659 
01660 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
01661 {
01662   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
01663     DiagDirection direction = GetTunnelBridgeDirection(tile);
01664     Axis axis = DiagDirToAxis(direction);
01665     CommandCost res;
01666     uint z_old;
01667     Slope tileh_old = GetTileSlope(tile, &z_old);
01668 
01669     /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
01670     if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
01671       CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
01672       res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
01673     } else {
01674       CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
01675       res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
01676     }
01677 
01678     /* Surface slope is valid and remains unchanged? */
01679     if (res.Succeeded() && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
01680   }
01681 
01682   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01683 }
01684 
01685 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
01686   DrawTile_TunnelBridge,           // draw_tile_proc
01687   GetSlopeZ_TunnelBridge,          // get_slope_z_proc
01688   ClearTile_TunnelBridge,          // clear_tile_proc
01689   NULL,                            // add_accepted_cargo_proc
01690   GetTileDesc_TunnelBridge,        // get_tile_desc_proc
01691   GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
01692   NULL,                            // click_tile_proc
01693   NULL,                            // animate_tile_proc
01694   TileLoop_TunnelBridge,           // tile_loop_clear
01695   ChangeTileOwner_TunnelBridge,    // change_tile_owner_clear
01696   NULL,                            // add_produced_cargo_proc
01697   VehicleEnter_TunnelBridge,       // vehicle_enter_tile_proc
01698   GetFoundation_TunnelBridge,      // get_foundation_proc
01699   TerraformTile_TunnelBridge,      // terraform_tile_proc
01700 };

Generated on Thu Jan 20 22:57:43 2011 for OpenTTD by  doxygen 1.6.1