tunnelbridge_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 
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 "station_map.h"
00027 #include "pathfinder/yapf/yapf_cache.h"
00028 #include "newgrf_sound.h"
00029 #include "autoslope.h"
00030 #include "tunnelbridge_map.h"
00031 #include "strings_func.h"
00032 #include "date_func.h"
00033 #include "clear_func.h"
00034 #include "vehicle_func.h"
00035 #include "vehicle_gui.h"
00036 #include "sound_func.h"
00037 #include "tunnelbridge.h"
00038 #include "cheat_type.h"
00039 #include "elrail_func.h"
00040 #include "pbs.h"
00041 #include "company_base.h"
00042 #include "newgrf_railtype.h"
00043 #include "object_base.h"
00044 #include "water.h"
00045 
00046 #include "table/sprites.h"
00047 #include "table/strings.h"
00048 #include "table/bridge_land.h"
00049 
00050 BridgeSpec _bridge[MAX_BRIDGES]; 
00051 TileIndex _build_tunnel_endtile; 
00052 
00054 static const int BRIDGE_Z_START = 3;
00055 
00057 void ResetBridges()
00058 {
00059   /* First, free sprite table data */
00060   for (BridgeType i = 0; i < MAX_BRIDGES; i++) {
00061     if (_bridge[i].sprite_table != NULL) {
00062       for (BridgePieces j = BRIDGE_PIECE_NORTH; j < BRIDGE_PIECE_INVALID; j++) free(_bridge[i].sprite_table[j]);
00063       free(_bridge[i].sprite_table);
00064     }
00065   }
00066 
00067   /* Then, wipe out current bidges */
00068   memset(&_bridge, 0, sizeof(_bridge));
00069   /* And finally, reinstall default data */
00070   memcpy(&_bridge, &_orig_bridge, sizeof(_orig_bridge));
00071 }
00072 
00079 int CalcBridgeLenCostFactor(int length)
00080 {
00081   if (length < 2) return length;
00082 
00083   length -= 2;
00084   int sum = 2;
00085   for (int delta = 1;; delta++) {
00086     for (int count = 0; count < delta; count++) {
00087       if (length == 0) return sum;
00088       sum += delta;
00089       length--;
00090     }
00091   }
00092 }
00093 
00100 Foundation GetBridgeFoundation(Slope tileh, Axis axis)
00101 {
00102   if (tileh == SLOPE_FLAT ||
00103       ((tileh == SLOPE_NE || tileh == SLOPE_SW) && axis == AXIS_X) ||
00104       ((tileh == SLOPE_NW || tileh == SLOPE_SE) && axis == AXIS_Y)) return FOUNDATION_NONE;
00105 
00106   return (HasSlopeHighestCorner(tileh) ? InclinedFoundation(axis) : FlatteningFoundation(tileh));
00107 }
00108 
00112 BridgeType GetFastestAvailableBridgeType(uint bridge_len)
00113 {
00114   BridgeType fastest_type = 0;
00115   uint16 fastest_speed = 0;
00116 
00117   for (BridgeType brd_type = 0; brd_type != MAX_BRIDGES; brd_type++) {
00118     CommandCost ret = CheckBridgeAvailability(brd_type, bridge_len, DC_NONE);
00119     if (!ret.Failed()) {
00120       /* bridge is accepted, compare speeds */
00121       const BridgeSpec *b = GetBridgeSpec(brd_type);
00122       if (b->speed >= fastest_speed) {
00123         fastest_type = brd_type;
00124         fastest_speed = b->speed;
00125       }
00126     }
00127   }
00128 
00129   return fastest_type;
00130 }
00131 
00139 bool HasBridgeFlatRamp(Slope tileh, Axis axis)
00140 {
00141   ApplyFoundationToSlope(GetBridgeFoundation(tileh, axis), &tileh);
00142   /* If the foundation slope is flat the bridge has a non-flat ramp and vice versa. */
00143   return (tileh != SLOPE_FLAT);
00144 }
00145 
00146 static inline const PalSpriteID *GetBridgeSpriteTable(int index, BridgePieces table)
00147 {
00148   const BridgeSpec *bridge = GetBridgeSpec(index);
00149   assert(table < BRIDGE_PIECE_INVALID);
00150   if (bridge->sprite_table == NULL || bridge->sprite_table[table] == NULL) {
00151     return _bridge_sprite_table[index][table];
00152   } else {
00153     return bridge->sprite_table[table];
00154   }
00155 }
00156 
00157 
00166 static CommandCost CheckBridgeSlopeNorth(Axis axis, Slope *tileh, uint *z)
00167 {
00168   Foundation f = GetBridgeFoundation(*tileh, axis);
00169   *z += ApplyFoundationToSlope(f, tileh);
00170 
00171   Slope valid_inclined = (axis == AXIS_X ? SLOPE_NE : SLOPE_NW);
00172   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00173 
00174   if (f == FOUNDATION_NONE) return CommandCost();
00175 
00176   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00177 }
00178 
00187 static CommandCost CheckBridgeSlopeSouth(Axis axis, Slope *tileh, uint *z)
00188 {
00189   Foundation f = GetBridgeFoundation(*tileh, axis);
00190   *z += ApplyFoundationToSlope(f, tileh);
00191 
00192   Slope valid_inclined = (axis == AXIS_X ? SLOPE_SW : SLOPE_SE);
00193   if ((*tileh != SLOPE_FLAT) && (*tileh != valid_inclined)) return CMD_ERROR;
00194 
00195   if (f == FOUNDATION_NONE) return CommandCost();
00196 
00197   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00198 }
00199 
00206 CommandCost CheckBridgeAvailability(BridgeType bridge_type, uint bridge_len, DoCommandFlag flags)
00207 {
00208   if (flags & DC_QUERY_COST) {
00209     if (bridge_len <= _settings_game.construction.max_bridge_length) return CommandCost();
00210     return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00211   }
00212 
00213   if (bridge_type >= MAX_BRIDGES) return CMD_ERROR;
00214 
00215   const BridgeSpec *b = GetBridgeSpec(bridge_type);
00216   if (b->avail_year > _cur_year) return CMD_ERROR;
00217 
00218   uint max = min(b->max_length, _settings_game.construction.max_bridge_length);
00219 
00220   if (b->min_length > bridge_len) return CMD_ERROR;
00221   if (bridge_len <= max) return CommandCost();
00222   return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00223 }
00224 
00237 CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00238 {
00239   RailType railtype = INVALID_RAILTYPE;
00240   RoadTypes roadtypes = ROADTYPES_NONE;
00241 
00242   /* unpack parameters */
00243   BridgeType bridge_type = GB(p2, 0, 8);
00244 
00245   if (!IsValidTile(p1)) return_cmd_error(STR_ERROR_BRIDGE_THROUGH_MAP_BORDER);
00246 
00247   TransportType transport_type = Extract<TransportType, 15, 2>(p2);
00248 
00249   /* type of bridge */
00250   switch (transport_type) {
00251     case TRANSPORT_ROAD:
00252       roadtypes = Extract<RoadTypes, 8, 2>(p2);
00253       if (!HasExactlyOneBit(roadtypes) || !HasRoadTypesAvail(_current_company, roadtypes)) return CMD_ERROR;
00254       break;
00255 
00256     case TRANSPORT_RAIL:
00257       railtype = Extract<RailType, 8, 4>(p2);
00258       if (!ValParamRailtype(railtype)) return CMD_ERROR;
00259       break;
00260 
00261     case TRANSPORT_WATER:
00262       break;
00263 
00264     default:
00265       /* Airports don't have bridges. */
00266       return CMD_ERROR;
00267   }
00268   TileIndex tile_start = p1;
00269   TileIndex tile_end = end_tile;
00270 
00271   if (tile_start == tile_end) {
00272     return_cmd_error(STR_ERROR_CAN_T_START_AND_END_ON);
00273   }
00274 
00275   Axis direction;
00276   if (TileX(tile_start) == TileX(tile_end)) {
00277     direction = AXIS_Y;
00278   } else if (TileY(tile_start) == TileY(tile_end)) {
00279     direction = AXIS_X;
00280   } else {
00281     return_cmd_error(STR_ERROR_START_AND_END_MUST_BE_IN);
00282   }
00283 
00284   if (tile_end < tile_start) Swap(tile_start, tile_end);
00285 
00286   uint bridge_len = GetTunnelBridgeLength(tile_start, tile_end);
00287   if (transport_type != TRANSPORT_WATER) {
00288     /* set and test bridge length, availability */
00289     CommandCost ret = CheckBridgeAvailability(bridge_type, bridge_len, flags);
00290     if (ret.Failed()) return ret;
00291   } else {
00292     if (bridge_len > _settings_game.construction.max_bridge_length) return_cmd_error(STR_ERROR_BRIDGE_TOO_LONG);
00293   }
00294 
00295   uint z_start;
00296   uint z_end;
00297   Slope tileh_start = GetTileSlope(tile_start, &z_start);
00298   Slope tileh_end = GetTileSlope(tile_end, &z_end);
00299   bool pbs_reservation = false;
00300 
00301   CommandCost terraform_cost_north = CheckBridgeSlopeNorth(direction, &tileh_start, &z_start);
00302   CommandCost terraform_cost_south = CheckBridgeSlopeSouth(direction, &tileh_end,   &z_end);
00303 
00304   /* Aqueducts can't be built of flat land. */
00305   if (transport_type == TRANSPORT_WATER && (tileh_start == SLOPE_FLAT || tileh_end == SLOPE_FLAT)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00306   if (z_start != z_end) return_cmd_error(STR_ERROR_BRIDGEHEADS_NOT_SAME_HEIGHT);
00307 
00308   CommandCost cost(EXPENSES_CONSTRUCTION);
00309   Owner owner;
00310   if (IsBridgeTile(tile_start) && IsBridgeTile(tile_end) &&
00311       GetOtherBridgeEnd(tile_start) == tile_end &&
00312       GetTunnelBridgeTransportType(tile_start) == transport_type) {
00313     /* Replace a current bridge. */
00314 
00315     /* If this is a railway bridge, make sure the railtypes match. */
00316     if (transport_type == TRANSPORT_RAIL && GetRailType(tile_start) != railtype) {
00317       return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00318     }
00319 
00320     /* Do not replace town bridges with lower speed bridges. */
00321     if (!(flags & DC_QUERY_COST) && IsTileOwner(tile_start, OWNER_TOWN) &&
00322         GetBridgeSpec(bridge_type)->speed < GetBridgeSpec(GetBridgeType(tile_start))->speed) {
00323       Town *t = ClosestTownFromTile(tile_start, UINT_MAX);
00324 
00325       if (t == NULL) {
00326         return CMD_ERROR;
00327       } else {
00328         SetDParam(0, t->index);
00329         return_cmd_error(STR_ERROR_LOCAL_AUTHORITY_REFUSES_TO_ALLOW_THIS);
00330       }
00331     }
00332 
00333     /* Do not replace the bridge with the same bridge type. */
00334     if (!(flags & DC_QUERY_COST) && bridge_type == GetBridgeType(tile_start)) {
00335       return_cmd_error(STR_ERROR_ALREADY_BUILT);
00336     }
00337 
00338     /* Do not allow replacing another company's bridges. */
00339     if (!IsTileOwner(tile_start, _current_company) && !IsTileOwner(tile_start, OWNER_TOWN)) {
00340       return_cmd_error(STR_ERROR_AREA_IS_OWNED_BY_ANOTHER);
00341     }
00342 
00343     cost.AddCost((bridge_len + 1) * _price[PR_CLEAR_BRIDGE]); // The cost of clearing the current bridge.
00344     owner = GetTileOwner(tile_start);
00345 
00346     switch (transport_type) {
00347       case TRANSPORT_RAIL:
00348         /* Keep the reservation, the path stays valid. */
00349         pbs_reservation = HasTunnelBridgeReservation(tile_start);
00350         break;
00351 
00352       case TRANSPORT_ROAD:
00353         /* Do not remove road types when upgrading a bridge */
00354         roadtypes |= GetRoadTypes(tile_start);
00355         break;
00356 
00357       default: break;
00358     }
00359   } else {
00360     /* Build a new bridge. */
00361 
00362     bool allow_on_slopes = (_settings_game.construction.build_on_slopes && transport_type != TRANSPORT_WATER);
00363 
00364     /* Try and clear the start landscape */
00365     CommandCost ret = DoCommand(tile_start, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00366     if (ret.Failed()) return ret;
00367     cost = ret;
00368 
00369     if (terraform_cost_north.Failed() || (terraform_cost_north.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00370     cost.AddCost(terraform_cost_north);
00371 
00372     /* Try and clear the end landscape */
00373     ret = DoCommand(tile_end, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00374     if (ret.Failed()) return ret;
00375     cost.AddCost(ret);
00376 
00377     /* false - end tile slope check */
00378     if (terraform_cost_south.Failed() || (terraform_cost_south.GetCost() != 0 && !allow_on_slopes)) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00379     cost.AddCost(terraform_cost_south);
00380 
00381     const TileIndex heads[] = {tile_start, tile_end};
00382     for (int i = 0; i < 2; i++) {
00383       if (MayHaveBridgeAbove(heads[i])) {
00384         if (IsBridgeAbove(heads[i])) {
00385           TileIndex north_head = GetNorthernBridgeEnd(heads[i]);
00386 
00387           if (direction == GetBridgeAxis(heads[i])) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00388 
00389           if (z_start + TILE_HEIGHT == GetBridgeHeight(north_head)) {
00390             return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00391           }
00392         }
00393       }
00394     }
00395 
00396     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00397     for (TileIndex tile = tile_start + delta; tile != tile_end; tile += delta) {
00398       if (GetTileMaxZ(tile) > z_start) return_cmd_error(STR_ERROR_BRIDGE_TOO_LOW_FOR_TERRAIN);
00399 
00400       if (z_start + TILE_HEIGHT > (TileHeight(tile) + MAX_BRIDGE_HEIGHT) * TILE_HEIGHT) {
00401         /* z_start seems to be one height level below the bridge level in all cases.
00402          * So add one TILE_HEIGHT. Then compare, if the currently tested tile is to low.
00403          * If yes, we have a problem... */
00404         return_cmd_error(STR_ERROR_BRIDGE_TOO_HIGH_FOR_TERRAIN);
00405       }
00406 
00407       if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) {
00408         /* Disallow crossing bridges for the time being */
00409         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00410       }
00411 
00412       switch (GetTileType(tile)) {
00413         case MP_WATER:
00414           if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
00415           break;
00416 
00417         case MP_RAILWAY:
00418           if (!IsPlainRail(tile)) goto not_valid_below;
00419           break;
00420 
00421         case MP_ROAD:
00422           if (IsRoadDepot(tile)) goto not_valid_below;
00423           break;
00424 
00425         case MP_TUNNELBRIDGE:
00426           if (IsTunnel(tile)) break;
00427           if (direction == DiagDirToAxis(GetTunnelBridgeDirection(tile))) goto not_valid_below;
00428           if (z_start < GetBridgeHeight(tile)) goto not_valid_below;
00429           break;
00430 
00431         case MP_OBJECT: {
00432           const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
00433           if ((spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) == 0) goto not_valid_below;
00434           if (GetTileMaxZ(tile) + spec->height * TILE_HEIGHT > z_start) goto not_valid_below;
00435           break;
00436         }
00437 
00438         case MP_CLEAR:
00439           break;
00440 
00441         default:
00442   not_valid_below:;
00443           /* try and clear the middle landscape */
00444           ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00445           if (ret.Failed()) return ret;
00446           cost.AddCost(ret);
00447           break;
00448       }
00449 
00450       if (flags & DC_EXEC) {
00451         /* We do this here because when replacing a bridge with another
00452          * type calling SetBridgeMiddle isn't needed. After all, the
00453          * tile alread has the has_bridge_above bits set. */
00454         SetBridgeMiddle(tile, direction);
00455       }
00456     }
00457 
00458     owner = _current_company;
00459   }
00460 
00461   /* do the drill? */
00462   if (flags & DC_EXEC) {
00463     DiagDirection dir = AxisToDiagDir(direction);
00464 
00465     switch (transport_type) {
00466       case TRANSPORT_RAIL:
00467         MakeRailBridgeRamp(tile_start, owner, bridge_type, dir,                 railtype);
00468         MakeRailBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), railtype);
00469         SetTunnelBridgeReservation(tile_start, pbs_reservation);
00470         SetTunnelBridgeReservation(tile_end,   pbs_reservation);
00471         break;
00472 
00473       case TRANSPORT_ROAD:
00474         MakeRoadBridgeRamp(tile_start, owner, bridge_type, dir,                 roadtypes);
00475         MakeRoadBridgeRamp(tile_end,   owner, bridge_type, ReverseDiagDir(dir), roadtypes);
00476         break;
00477 
00478       case TRANSPORT_WATER:
00479         MakeAqueductBridgeRamp(tile_start, owner, dir);
00480         MakeAqueductBridgeRamp(tile_end,   owner, ReverseDiagDir(dir));
00481         break;
00482 
00483       default:
00484         NOT_REACHED();
00485     }
00486 
00487     /* Mark all tiles dirty */
00488     TileIndexDiff delta = (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
00489     for (TileIndex tile = tile_start; tile <= tile_end; tile += delta) {
00490       MarkTileDirtyByTile(tile);
00491     }
00492   }
00493 
00494   if ((flags & DC_EXEC) && transport_type == TRANSPORT_RAIL) {
00495     Track track = AxisToTrack(direction);
00496     AddSideToSignalBuffer(tile_start, INVALID_DIAGDIR, _current_company);
00497     YapfNotifyTrackLayoutChange(tile_start, track);
00498   }
00499 
00500   /* for human player that builds the bridge he gets a selection to choose from bridges (DC_QUERY_COST)
00501    * It's unnecessary to execute this command every time for every bridge. So it is done only
00502    * and cost is computed in "bridge_gui.c". For AI, Towns this has to be of course calculated
00503    */
00504   Company *c = Company::GetIfValid(_current_company);
00505   if (!(flags & DC_QUERY_COST) || (c != NULL && c->is_ai)) {
00506     bridge_len += 2; // begin and end tiles/ramps
00507 
00508     switch (transport_type) {
00509       case TRANSPORT_ROAD: cost.AddCost(bridge_len * _price[PR_BUILD_ROAD] * 2); break;
00510       case TRANSPORT_RAIL: cost.AddCost(bridge_len * RailBuildCost(railtype)); break;
00511       default: break;
00512     }
00513 
00514     if (c != NULL) bridge_len = CalcBridgeLenCostFactor(bridge_len);
00515 
00516     if (transport_type != TRANSPORT_WATER) {
00517       cost.AddCost((int64)bridge_len * _price[PR_BUILD_BRIDGE] * GetBridgeSpec(bridge_type)->price >> 8);
00518     } else {
00519       /* Aqueducts use a separate base cost. */
00520       cost.AddCost((int64)bridge_len * _price[PR_BUILD_AQUEDUCT]);
00521     }
00522 
00523   }
00524 
00525   return cost;
00526 }
00527 
00537 bool IsCrossableWater(TileIndex end_tile, TileIndexDiff delta, DiagDirection direction)
00538 {
00539   bool crossed_water = false; 
00540   uint end_z; // chunnel patch v18 ...changed to uint because of old source.
00541   /* Number of tiles after crossing water until end of tunnel */
00542   int end_tiles = 1;
00543   Slope end_tileh = GetTileSlope(end_tile, NULL);
00544 
00545   if (end_tileh != InclinedSlope(ReverseDiagDir(direction))) return false;
00546 
00547   for (;;) {
00548     end_tile += delta;
00549     if (!IsValidTile(end_tile)) break;
00550     if (crossed_water) end_tiles++;
00551     end_tileh = GetTileSlope(end_tile, &end_z);
00552     if (end_z == 0) {
00553       if (end_tileh == SLOPE_FLAT) {
00554         if (!(IsWaterTile(end_tile) || IsBuoyTile(end_tile))) break;
00555       } else {
00556         if (end_tiles > 1) {
00557           return (end_tiles > 3 && end_tiles < 7);
00558         } else if (end_tileh == InclinedSlope(direction)) {
00559           crossed_water = true;
00560         } else {
00561           break;
00562         }
00563       }
00564     }
00565   }
00566   return false;
00567 }
00568 
00579 CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00580 {
00581   TransportType transport_type = Extract<TransportType, 8, 2>(p1);
00582 
00583   RailType railtype = INVALID_RAILTYPE;
00584   RoadTypes rts = ROADTYPES_NONE;
00585   _build_tunnel_endtile = 0;
00586   switch (transport_type) {
00587     case TRANSPORT_RAIL:
00588       railtype = Extract<RailType, 0, 4>(p1);
00589       if (!ValParamRailtype(railtype)) return CMD_ERROR;
00590       break;
00591 
00592     case TRANSPORT_ROAD:
00593       rts = Extract<RoadTypes, 0, 2>(p1);
00594       if (!HasExactlyOneBit(rts) || !HasRoadTypesAvail(_current_company, rts)) return CMD_ERROR;
00595       break;
00596 
00597     default: return CMD_ERROR;
00598   }
00599 
00600   uint start_z;
00601   uint end_z;
00602   Slope start_tileh = GetTileSlope(start_tile, &start_z);
00603   DiagDirection direction = GetInclinedSlopeDirection(start_tileh);
00604   if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE_FOR_TUNNEL);
00605 
00606   if (HasTileWaterGround(start_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00607 
00608   CommandCost ret = DoCommand(start_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00609   if (ret.Failed()) return ret;
00610 
00611   /* XXX - do NOT change 'ret' in the loop, as it is used as the price
00612    * for the clearing of the entrance of the tunnel. Assigning it to
00613    * cost before the loop will yield different costs depending on start-
00614    * position, because of increased-cost-by-length: 'cost += cost >> 3' */
00615 
00616   TileIndexDiff delta = TileOffsByDiagDir(direction);
00617   DiagDirection tunnel_in_way_dir;
00618   if (DiagDirToAxis(direction) == AXIS_Y) {
00619     tunnel_in_way_dir = (TileX(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SW : DIAGDIR_NE;
00620   } else {
00621     tunnel_in_way_dir = (TileY(start_tile) < (MapMaxX() / 2)) ? DIAGDIR_SE : DIAGDIR_NW;
00622   }
00623 
00624   TileIndex end_tile = start_tile;
00625 
00626   /* Tile shift coeficient. Will decrease for very long tunnels to avoid exponential growth of price*/
00627   int tiles_coef = 3;
00628   /* Number of tiles from start of tunnel */
00629   int tiles = 0;
00630   /* Number of tiles at which the cost increase coefficient per tile is halved */
00631   int tiles_bump = 25;
00632 
00633   /* Flag used while building crossing-water tunnel.
00634    * One stretch of water only.
00635    * 0 = Didn't cross water.
00636    * 1 = Not allowed to cross water.
00637    * 2 = Crossing water. 
00638    * 3 = Finished crossing water. */
00639   int pass_water = 0;  
00640 
00641   CommandCost cost(EXPENSES_CONSTRUCTION);
00642   Slope end_tileh;
00643   for (;;) {
00644     end_tile += delta;
00645     if (!IsValidTile(end_tile)) return_cmd_error(STR_ERROR_TUNNEL_THROUGH_MAP_BORDER);
00646     end_tileh = GetTileSlope(end_tile, &end_z);
00647 
00648     if (start_z == end_z) {
00649       if (start_z > 0) break;
00650       /* Tunnels crossing water only allowed at sea level. z == 0 */
00651       if (end_tileh != SLOPE_FLAT) {
00652         if (pass_water == 2) pass_water = 3;
00653         if (pass_water == 0) {
00654           /* 2 tiles between entrance and coast tile. */
00655           (tiles > 1 && tiles < 5 && IsCrossableWater(end_tile, delta, direction)) ? pass_water = 2 : pass_water = 1;
00656         }
00657 
00658         if (pass_water == 1) break;
00659         if (pass_water == 3) pass_water = 1; // Finish at next suitable inclined tile.
00660       }
00661     }
00662 
00663     if (!_cheats.crossing_tunnels.value && IsTunnelInWayDir(end_tile, start_z, tunnel_in_way_dir)) {
00664       return_cmd_error(STR_ERROR_ANOTHER_TUNNEL_IN_THE_WAY);
00665     }
00666 
00667     tiles++;
00668     if (tiles == tiles_bump) {
00669       tiles_coef++;
00670       tiles_bump *= 2;
00671     }
00672 
00673     cost.AddCost(_price[PR_BUILD_TUNNEL]);
00674     cost.AddCost(cost.GetCost() >> tiles_coef); // add a multiplier for longer tunnels
00675   }
00676 
00677   /* Add the cost of the entrance */
00678   cost.AddCost(_price[PR_BUILD_TUNNEL]);
00679   cost.AddCost(ret);
00680 
00681   /* if the command fails from here on we want the end tile to be highlighted */
00682   _build_tunnel_endtile = end_tile;
00683 
00684   if (tiles > _settings_game.construction.max_tunnel_length) return_cmd_error(STR_ERROR_TUNNEL_TOO_LONG);
00685 
00686   if (HasTileWaterGround(end_tile)) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00687 
00688   /* Clear the tile in any case */
00689   ret = DoCommand(end_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00690   if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
00691   cost.AddCost(ret);
00692 
00693   /* slope of end tile must be complementary to the slope of the start tile */
00694   if (end_tileh != ComplementSlope(start_tileh)) {
00695     /* Mark the tile as already cleared for the terraform command.
00696      * Do this for all tiles (like trees), not only objects. */
00697     ClearedObjectArea *coa = FindClearedObject(end_tile);
00698     if (coa == NULL) {
00699       coa = _cleared_object_areas.Append();
00700       coa->first_tile = end_tile;
00701       coa->area = TileArea(end_tile, 1, 1);
00702     }
00703 
00704     /* Hide the tile from the terraforming command */
00705     TileIndex old_first_tile = coa->first_tile;
00706     coa->first_tile = INVALID_TILE;
00707     ret = DoCommand(end_tile, end_tileh & start_tileh, 0, flags, CMD_TERRAFORM_LAND);
00708     coa->first_tile = old_first_tile;
00709     if (ret.Failed()) return_cmd_error(STR_ERROR_UNABLE_TO_EXCAVATE_LAND);
00710     cost.AddCost(ret);
00711   }
00712   cost.AddCost(_price[PR_BUILD_TUNNEL]);
00713 
00714   /* Pay for the rail/road in the tunnel including entrances */
00715   switch (transport_type) {
00716     case TRANSPORT_ROAD: cost.AddCost((tiles + 2) * _price[PR_BUILD_ROAD] * 2); break;
00717     case TRANSPORT_RAIL: cost.AddCost((tiles + 2) * RailBuildCost(railtype)); break;
00718     default: break;
00719   }
00720 
00721   if (flags & DC_EXEC) {
00722     if (transport_type == TRANSPORT_RAIL) {
00723       MakeRailTunnel(start_tile, _current_company, direction,                 railtype);
00724       MakeRailTunnel(end_tile,   _current_company, ReverseDiagDir(direction), railtype);
00725       AddSideToSignalBuffer(start_tile, INVALID_DIAGDIR, _current_company);
00726       YapfNotifyTrackLayoutChange(start_tile, DiagDirToDiagTrack(direction));
00727     } else {
00728       MakeRoadTunnel(start_tile, _current_company, direction,                 rts);
00729       MakeRoadTunnel(end_tile,   _current_company, ReverseDiagDir(direction), rts);
00730     }
00731   }
00732 
00733   return cost;
00734 }
00735 
00736 
00742 static inline CommandCost CheckAllowRemoveTunnelBridge(TileIndex tile)
00743 {
00744   /* Floods can remove anything as well as the scenario editor */
00745   if (_current_company == OWNER_WATER || _game_mode == GM_EDITOR) return CommandCost();
00746 
00747   switch (GetTunnelBridgeTransportType(tile)) {
00748     case TRANSPORT_ROAD: {
00749       RoadTypes rts = GetRoadTypes(tile);
00750       Owner road_owner = _current_company;
00751       Owner tram_owner = _current_company;
00752 
00753       if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
00754       if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
00755 
00756       /* We can remove unowned road and if the town allows it */
00757       if (road_owner == OWNER_TOWN && !(_settings_game.construction.extra_dynamite || _cheats.magic_bulldozer.value)) {
00758         return CheckTileOwnership(tile);
00759       }
00760       if (road_owner == OWNER_NONE || road_owner == OWNER_TOWN) road_owner = _current_company;
00761       if (tram_owner == OWNER_NONE) tram_owner = _current_company;
00762 
00763       CommandCost ret = CheckOwnership(road_owner, tile);
00764       if (ret.Succeeded()) ret = CheckOwnership(tram_owner, tile);
00765       return ret;
00766     }
00767 
00768     case TRANSPORT_RAIL:
00769     case TRANSPORT_WATER:
00770       return CheckOwnership(GetTileOwner(tile));
00771 
00772     default: NOT_REACHED();
00773   }
00774 }
00775 
00782 static CommandCost DoClearTunnel(TileIndex tile, DoCommandFlag flags)
00783 {
00784   CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
00785   if (ret.Failed()) return ret;
00786 
00787   TileIndex endtile = GetOtherTunnelEnd(tile);
00788 
00789   ret = TunnelBridgeIsFree(tile, endtile);
00790   if (ret.Failed()) return ret;
00791 
00792   _build_tunnel_endtile = endtile;
00793 
00794   Town *t = NULL;
00795   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00796     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00797 
00798     /* Check if you are allowed to remove the tunnel owned by a town
00799      * Removal depends on difficulty settings */
00800     CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
00801     if (ret.Failed()) return ret;
00802   }
00803 
00804   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00805    * you have a "Poor" (0) town rating */
00806   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00807     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00808   }
00809 
00810   if (flags & DC_EXEC) {
00811     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
00812       /* We first need to request values before calling DoClearSquare */
00813       DiagDirection dir = GetTunnelBridgeDirection(tile);
00814       Track track = DiagDirToDiagTrack(dir);
00815       Owner owner = GetTileOwner(tile);
00816 
00817       Train *v = NULL;
00818       if (HasTunnelBridgeReservation(tile)) {
00819         v = GetTrainForReservation(tile, track);
00820         if (v != NULL) FreeTrainTrackReservation(v);
00821       }
00822 
00823       DoClearSquare(tile);
00824       DoClearSquare(endtile);
00825 
00826       /* cannot use INVALID_DIAGDIR for signal update because the tunnel doesn't exist anymore */
00827       AddSideToSignalBuffer(tile,    ReverseDiagDir(dir), owner);
00828       AddSideToSignalBuffer(endtile, dir,                 owner);
00829 
00830       YapfNotifyTrackLayoutChange(tile,    track);
00831       YapfNotifyTrackLayoutChange(endtile, track);
00832 
00833       if (v != NULL) TryPathReserve(v);
00834     } else {
00835       DoClearSquare(tile);
00836       DoClearSquare(endtile);
00837     }
00838   }
00839   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_TUNNEL] * (GetTunnelBridgeLength(tile, endtile) + 2));
00840 }
00841 
00842 
00849 static CommandCost DoClearBridge(TileIndex tile, DoCommandFlag flags)
00850 {
00851   CommandCost ret = CheckAllowRemoveTunnelBridge(tile);
00852   if (ret.Failed()) return ret;
00853 
00854   TileIndex endtile = GetOtherBridgeEnd(tile);
00855 
00856   ret = TunnelBridgeIsFree(tile, endtile);
00857   if (ret.Failed()) return ret;
00858 
00859   DiagDirection direction = GetTunnelBridgeDirection(tile);
00860   TileIndexDiff delta = TileOffsByDiagDir(direction);
00861 
00862   Town *t = NULL;
00863   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00864     t = ClosestTownFromTile(tile, UINT_MAX); // town penalty rating
00865 
00866     /* Check if you are allowed to remove the bridge owned by a town
00867      * Removal depends on difficulty settings */
00868     CommandCost ret = CheckforTownRating(flags, t, TUNNELBRIDGE_REMOVE);
00869     if (ret.Failed()) return ret;
00870   }
00871 
00872   /* checks if the owner is town then decrease town rating by RATING_TUNNEL_BRIDGE_DOWN_STEP until
00873    * you have a "Poor" (0) town rating */
00874   if (IsTileOwner(tile, OWNER_TOWN) && _game_mode != GM_EDITOR) {
00875     ChangeTownRating(t, RATING_TUNNEL_BRIDGE_DOWN_STEP, RATING_TUNNEL_BRIDGE_MINIMUM, flags);
00876   }
00877 
00878   Money base_cost = (GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) ? _price[PR_CLEAR_BRIDGE] : _price[PR_CLEAR_AQUEDUCT];
00879 
00880   if (flags & DC_EXEC) {
00881     /* read this value before actual removal of bridge */
00882     bool rail = GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL;
00883     Owner owner = GetTileOwner(tile);
00884     uint height = GetBridgeHeight(tile);
00885     Train *v = NULL;
00886 
00887     if (rail && HasTunnelBridgeReservation(tile)) {
00888       v = GetTrainForReservation(tile, DiagDirToDiagTrack(direction));
00889       if (v != NULL) FreeTrainTrackReservation(v);
00890     }
00891 
00892     DoClearSquare(tile);
00893     DoClearSquare(endtile);
00894     for (TileIndex c = tile + delta; c != endtile; c += delta) {
00895       /* do not let trees appear from 'nowhere' after removing bridge */
00896       if (IsNormalRoadTile(c) && GetRoadside(c) == ROADSIDE_TREES) {
00897         uint minz = GetTileMaxZ(c) + 3 * TILE_HEIGHT;
00898         if (height < minz) SetRoadside(c, ROADSIDE_PAVED);
00899       }
00900       ClearBridgeMiddle(c);
00901       MarkTileDirtyByTile(c);
00902     }
00903 
00904     if (rail) {
00905       /* cannot use INVALID_DIAGDIR for signal update because the bridge doesn't exist anymore */
00906       AddSideToSignalBuffer(tile,    ReverseDiagDir(direction), owner);
00907       AddSideToSignalBuffer(endtile, direction,                 owner);
00908 
00909       Track track = DiagDirToDiagTrack(direction);
00910       YapfNotifyTrackLayoutChange(tile,    track);
00911       YapfNotifyTrackLayoutChange(endtile, track);
00912 
00913       if (v != NULL) TryPathReserve(v, true);
00914     }
00915   }
00916 
00917   return CommandCost(EXPENSES_CONSTRUCTION, (GetTunnelBridgeLength(tile, endtile) + 2) * base_cost);
00918 }
00919 
00926 static CommandCost ClearTile_TunnelBridge(TileIndex tile, DoCommandFlag flags)
00927 {
00928   if (IsTunnel(tile)) {
00929     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_TUNNEL_FIRST);
00930     return DoClearTunnel(tile, flags);
00931   } else { // IsBridge(tile)
00932     if (flags & DC_AUTO) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00933     return DoClearBridge(tile, flags);
00934   }
00935 }
00936 
00947 static inline void DrawPillar(const PalSpriteID *psid, int x, int y, int z, int w, int h, const SubSprite *subsprite)
00948 {
00949   static const int PILLAR_Z_OFFSET = TILE_HEIGHT - BRIDGE_Z_START; 
00950   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);
00951 }
00952 
00964 static int DrawPillarColumn(int z_bottom, int z_top, const PalSpriteID *psid, int x, int y, int w, int h)
00965 {
00966   int cur_z;
00967   for (cur_z = z_top; cur_z >= z_bottom; cur_z -= TILE_HEIGHT) {
00968     DrawPillar(psid, x, y, cur_z, w, h, NULL);
00969   }
00970   return cur_z;
00971 }
00972 
00984 static void DrawBridgePillars(const PalSpriteID *psid, const TileInfo *ti, Axis axis, bool drawfarpillar, int x, int y, int z_bridge)
00985 {
00986   static const int bounding_box_size[2]  = {16, 2}; 
00987   static const int back_pillar_offset[2] = { 0, 9}; 
00988 
00989   static const int INF = 1000; 
00990   static const SubSprite half_pillar_sub_sprite[2][2] = {
00991     { {  -14, -INF, INF, INF }, { -INF, -INF, -15, INF } }, // X axis, north and south
00992     { { -INF, -INF,  15, INF }, {   16, -INF, INF, INF } }, // Y axis, north and south
00993   };
00994 
00995   if (psid->sprite == 0) return;
00996 
00997   /* Determine ground height under pillars */
00998   DiagDirection south_dir = AxisToDiagDir(axis);
00999   int z_front_north = ti->z;
01000   int z_back_north = ti->z;
01001   int z_front_south = ti->z;
01002   int z_back_south = ti->z;
01003   GetSlopeZOnEdge(ti->tileh, south_dir, &z_front_south, &z_back_south);
01004   GetSlopeZOnEdge(ti->tileh, ReverseDiagDir(south_dir), &z_front_north, &z_back_north);
01005 
01006   /* Shared height of pillars */
01007   int z_front = max(z_front_north, z_front_south);
01008   int z_back = max(z_back_north, z_back_south);
01009 
01010   /* x and y size of bounding-box of pillars */
01011   int w = bounding_box_size[axis];
01012   int h = bounding_box_size[OtherAxis(axis)];
01013   /* sprite position of back facing pillar */
01014   int x_back = x - back_pillar_offset[axis];
01015   int y_back = y - back_pillar_offset[OtherAxis(axis)];
01016 
01017   /* Draw front pillars */
01018   int bottom_z = DrawPillarColumn(z_front, z_bridge, psid, x, y, w, h);
01019   if (z_front_north < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
01020   if (z_front_south < z_front) DrawPillar(psid, x, y, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
01021 
01022   /* Draw back pillars, skip top two parts, which are hidden by the bridge */
01023   int z_bridge_back = z_bridge - 2 * (int)TILE_HEIGHT;
01024   if (drawfarpillar && (z_back_north <= z_bridge_back || z_back_south <= z_bridge_back)) {
01025     bottom_z = DrawPillarColumn(z_back, z_bridge_back, psid, x_back, y_back, w, h);
01026     if (z_back_north < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][0]);
01027     if (z_back_south < z_back) DrawPillar(psid, x_back, y_back, bottom_z, w, h, &half_pillar_sub_sprite[axis][1]);
01028   }
01029 }
01030 
01040 static void DrawBridgeTramBits(int x, int y, int z, int offset, bool overlay, bool head)
01041 {
01042   static const SpriteID tram_offsets[2][6] = { { 107, 108, 109, 110, 111, 112 }, { 4, 5, 15, 16, 17, 18 } };
01043   static const SpriteID back_offsets[6]    =   {  95,  96,  99, 102, 100, 101 };
01044   static const SpriteID front_offsets[6]   =   {  97,  98, 103, 106, 104, 105 };
01045 
01046   static const uint size_x[6] = {  1, 16, 16,  1, 16,  1 };
01047   static const uint size_y[6] = { 16,  1,  1, 16,  1, 16 };
01048   static const uint front_bb_offset_x[6] = { 15,  0,  0, 15,  0, 15 };
01049   static const uint front_bb_offset_y[6] = {  0, 15, 15,  0, 15,  0 };
01050 
01051   /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
01052    * The bounding boxes here are the same as for bridge front/roof */
01053   if (head || !IsInvisibilitySet(TO_BRIDGES)) {
01054     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + tram_offsets[overlay][offset], PAL_NONE,
01055       x, y, size_x[offset], size_y[offset], 0x28, z,
01056       !head && IsTransparencySet(TO_BRIDGES));
01057   }
01058 
01059   /* Do not draw catenary if it is set invisible */
01060   if (!IsInvisibilitySet(TO_CATENARY)) {
01061     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + back_offsets[offset], PAL_NONE,
01062       x, y, size_x[offset], size_y[offset], 0x28, z,
01063       IsTransparencySet(TO_CATENARY));
01064   }
01065 
01066   /* Start a new SpriteCombine for the front part */
01067   EndSpriteCombine();
01068   StartSpriteCombine();
01069 
01070   /* For sloped sprites the bounding box needs to be higher, as the pylons stop on a higher point */
01071   if (!IsInvisibilitySet(TO_CATENARY)) {
01072     AddSortableSpriteToDraw(SPR_TRAMWAY_BASE + front_offsets[offset], PAL_NONE,
01073       x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,
01074       IsTransparencySet(TO_CATENARY), front_bb_offset_x[offset], front_bb_offset_y[offset]);
01075   }
01076 }
01077 
01079 static void DrawTunnelBridgeRampSignal(const TileInfo *ti)
01080 {
01081   bool side = (_settings_game.vehicle.road_side != 0) &&_settings_game.construction.signal_side;
01082 
01083   static const Point SignalPositions[2][4] = {
01084     {      /* Signals on the left side */
01085       {13,  3}, { 2, 13}, { 3,  4}, {13, 14}
01086     }, {   /* Signals on the right side */
01087       {14, 13}, { 3,  3}, {13,  2}, { 3, 13}
01088     }
01089   };
01090 
01091   uint position;
01092   DiagDirection dir = GetTunnelBridgeDirection(ti->tile);
01093   if (IsTunnelBridgeExit(ti->tile)) dir = ReverseDiagDir(dir);
01094 
01095   switch (dir) {
01096     default: NOT_REACHED();
01097     case DIAGDIR_NE: position = 0; break;
01098     case DIAGDIR_SE: position = 2; break;
01099     case DIAGDIR_SW: position = 1; break;
01100     case DIAGDIR_NW: position = 3; break;
01101   }
01102 
01103   uint x = ti->x + SignalPositions[side][position].x;
01104   uint y = ti->y + SignalPositions[side][position].y;
01105   uint z = ti->z;
01106   if (ti->tileh != SLOPE_FLAT && IsBridge(ti->tile)) z += 8; // sloped bridge head
01107   SignalVariant variant = (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC);
01108 
01109   SpriteID sprite;
01110   if (variant == SIG_ELECTRIC) {
01111     /* Normal electric signals are picked from original sprites. */
01112     sprite = SPR_ORIGINAL_SIGNALS_BASE + ((position << 1) + IsTunnelBridgeWithSignGreen(ti->tile));
01113   } else {
01114     /* All other signals are picked from add on sprites. */
01115     sprite = SPR_SIGNALS_BASE + ((SIGTYPE_NORMAL - 1) * 16 + variant * 64 + (position << 1) + IsTunnelBridgeWithSignGreen(ti->tile));
01116   }
01117 
01118   AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, TILE_HEIGHT, z, false, 0, 0, BB_Z_SEPARATOR);
01119 }
01120 
01121  /* Draws a signal on tunnel / bridge entrance tile. */
01122 static void DrawBrigeSignalOnMiddelPart(const TileInfo *ti, TileIndex bridge_start_tile, uint z)
01123 {
01124 
01125   uint bridge_signal_position = 0;
01126   int m2_position = 0;
01127 
01128   uint bridge_section = GetTunnelBridgeLength(ti->tile, bridge_start_tile) + 1;
01129   
01130   while (bridge_signal_position <= bridge_section) {
01131     bridge_signal_position += 4; // 4 tiles is block size, max 24 signals, 25 blocks * 4 = 102 on bridge of max length e.g. 100 tiles 
01132     if (bridge_signal_position == bridge_section) {
01133       bool side = (_settings_game.vehicle.road_side != 0) && _settings_game.construction.signal_side;
01134 
01135       static const Point SignalPositions[2][4] = {
01136         {      /* Signals on the left side */
01137           {13,  3}, { 2, 13}, { 3,  4}, {13, 14}
01138         }, {   /* Signals on the right side */
01139           {10, 13}, { 4,  3}, {13,  2}, { 3, 3}
01140         }
01141       };
01142       uint position;
01143 
01144       switch (GetTunnelBridgeDirection(bridge_start_tile)) {
01145         default: NOT_REACHED();
01146         case DIAGDIR_NE: position = 0; z += 8; break;
01147         case DIAGDIR_SE: position = 2; z += 8; break;
01148         case DIAGDIR_SW: position = 1; break;
01149         case DIAGDIR_NW: position = 3; break;
01150       }
01151 
01152 
01153       uint x = ti->x + SignalPositions[side][position].x;
01154       uint y = ti->y + SignalPositions[side][position].y;
01155 
01156       SignalVariant variant = (_cur_year < _settings_client.gui.semaphore_build_before ? SIG_SEMAPHORE : SIG_ELECTRIC);
01157 
01158       SpriteID sprite;
01159       if (variant == SIG_ELECTRIC) {
01160         /* Normal electric signals are picked from original sprites. */
01161         sprite = SPR_ORIGINAL_SIGNALS_BASE + ((position << 1) + !HasBit(_m[bridge_start_tile].m2, m2_position));
01162       } else {
01163         /* All other signals are picked from add on sprites. */
01164         sprite = SPR_SIGNALS_BASE + ((SIGTYPE_NORMAL - 1) * 16 + variant * 64 + (position << 1) + !HasBit(_m[bridge_start_tile].m2, m2_position));
01165       }
01166 
01167       AddSortableSpriteToDraw(sprite, PAL_NONE, x, y, 1, 1, TILE_HEIGHT, z, false, 0, 0, BB_Z_SEPARATOR);
01168     }
01169     m2_position++;
01170   }
01171 }
01172 
01186 static void DrawTile_TunnelBridge(TileInfo *ti)
01187 {
01188   TransportType transport_type = GetTunnelBridgeTransportType(ti->tile);
01189   DiagDirection tunnelbridge_direction = GetTunnelBridgeDirection(ti->tile);
01190 
01191   if (IsTunnel(ti->tile)) {
01192     /* Front view of tunnel bounding boxes:
01193      *
01194      *   122223  <- BB_Z_SEPARATOR
01195      *   1    3
01196      *   1    3                1,3 = empty helper BB
01197      *   1    3                  2 = SpriteCombine of tunnel-roof and catenary (tram & elrail)
01198      *
01199      */
01200 
01201     static const int _tunnel_BB[4][12] = {
01202       /*  tunnnel-roof  |  Z-separator  | tram-catenary
01203        * w  h  bb_x bb_y| x   y   w   h |bb_x bb_y w h */
01204       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // NE
01205       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // SE
01206       {  1,  0, -15, -14,  0, 15, 16,  1, 0, 1, 16, 15 }, // SW
01207       {  0,  1, -14, -15, 15,  0,  1, 16, 1, 0, 15, 16 }, // NW
01208     };
01209     const int *BB_data = _tunnel_BB[tunnelbridge_direction];
01210 
01211     bool catenary = false;
01212 
01213     SpriteID image;
01214     if (transport_type == TRANSPORT_RAIL) {
01215       image = GetRailTypeInfo(GetRailType(ti->tile))->base_sprites.tunnel;
01216     } else {
01217       image = SPR_TUNNEL_ENTRY_REAR_ROAD;
01218     }
01219 
01220     if (HasTunnelBridgeSnowOrDesert(ti->tile)) image += 32;
01221 
01222     image += tunnelbridge_direction * 2;
01223     DrawGroundSprite(image, PAL_NONE);
01224 
01225     /* PBS debugging, draw reserved tracks darker */
01226     if (_game_mode != GM_MENU && _settings_client.gui.show_track_reservation && (transport_type == TRANSPORT_RAIL && HasTunnelBridgeReservation(ti->tile))) {
01227       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01228       DrawGroundSprite(DiagDirToAxis(tunnelbridge_direction) == AXIS_X ? rti->base_sprites.single_x : rti->base_sprites.single_y, PALETTE_CRASH);
01229     }
01230 
01231     if (transport_type == TRANSPORT_ROAD) {
01232       RoadTypes rts = GetRoadTypes(ti->tile);
01233 
01234       if (HasBit(rts, ROADTYPE_TRAM)) {
01235         static const SpriteID tunnel_sprites[2][4] = { { 28, 78, 79, 27 }, {  5, 76, 77,  4 } };
01236 
01237         DrawGroundSprite(SPR_TRAMWAY_BASE + tunnel_sprites[rts - ROADTYPES_TRAM][tunnelbridge_direction], PAL_NONE);
01238 
01239         /* Do not draw wires if they are invisible */
01240         if (!IsInvisibilitySet(TO_CATENARY)) {
01241           catenary = true;
01242           StartSpriteCombine();
01243           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);
01244         }
01245       }
01246     } else {
01247       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01248       if (rti->UsesOverlay()) {
01249         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_TUNNEL);
01250         if (surface != 0) DrawGroundSprite(surface + tunnelbridge_direction, PAL_NONE);
01251       }
01252 
01253       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01254         /* Maybe draw pylons on the entry side */
01255         DrawCatenary(ti);
01256 
01257         catenary = true;
01258         StartSpriteCombine();
01259         /* Draw wire above the ramp */
01260         DrawCatenaryOnTunnel(ti);
01261       }
01262     }
01263 
01264     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);
01265 
01266     if (catenary) EndSpriteCombine();
01267 
01268     /* Add helper BB for sprite sorting that separates the tunnel from things beside of it. */
01269     AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, ti->x,              ti->y,              BB_data[6], BB_data[7], TILE_HEIGHT, ti->z);
01270     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);
01271 
01272     /*Draw signals for tunnel*/
01273     if (IsTunnelBridgeEntrance(ti->tile)) DrawTunnelBridgeRampSignal(ti);
01274 
01275     DrawBridgeMiddle(ti);
01276   } else { // IsBridge(ti->tile)
01277     const PalSpriteID *psid;
01278     int base_offset;
01279     bool ice = HasTunnelBridgeSnowOrDesert(ti->tile);
01280 
01281     if (transport_type == TRANSPORT_RAIL) {
01282       base_offset = GetRailTypeInfo(GetRailType(ti->tile))->bridge_offset;
01283       assert(base_offset != 8); // This one is used for roads
01284     } else {
01285       base_offset = 8;
01286     }
01287 
01288     /* as the lower 3 bits are used for other stuff, make sure they are clear */
01289     assert( (base_offset & 0x07) == 0x00);
01290 
01291     DrawFoundation(ti, GetBridgeFoundation(ti->tileh, DiagDirToAxis(tunnelbridge_direction)));
01292 
01293     /* HACK Wizardry to convert the bridge ramp direction into a sprite offset */
01294     base_offset += (6 - tunnelbridge_direction) % 4;
01295 
01296     if (ti->tileh == SLOPE_FLAT) base_offset += 4; // sloped bridge head
01297 
01298     /* Table number BRIDGE_PIECE_HEAD always refers to the bridge heads for any bridge type */
01299     if (transport_type != TRANSPORT_WATER) {
01300       psid = &GetBridgeSpriteTable(GetBridgeType(ti->tile), BRIDGE_PIECE_HEAD)[base_offset];
01301     } else {
01302       psid = _aqueduct_sprites + base_offset;
01303     }
01304 
01305     if (!ice) {
01306       TileIndex next = ti->tile + TileOffsByDiagDir(tunnelbridge_direction);
01307       if (ti->tileh != SLOPE_FLAT && ti->z == 0 && HasTileWaterClass(next) && GetWaterClass(next) == WATER_CLASS_SEA) {
01308         DrawShoreTile(ti->tileh);
01309       } else {
01310         DrawClearLandTile(ti, 3);
01311       }
01312     } else {
01313       DrawGroundSprite(SPR_FLAT_SNOW_DESERT_TILE + SlopeToSpriteOffset(ti->tileh), PAL_NONE);
01314     }
01315 
01316     /* draw ramp */
01317 
01318     /* Draw Trambits and PBS Reservation as SpriteCombine */
01319     if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
01320 
01321     /* HACK set the height of the BB of a sloped ramp to 1 so a vehicle on
01322      * it doesn't disappear behind it
01323      */
01324     /* Bridge heads are drawn solid no matter how invisibility/transparency is set */
01325     AddSortableSpriteToDraw(psid->sprite, psid->pal, ti->x, ti->y, 16, 16, ti->tileh == SLOPE_FLAT ? 0 : 8, ti->z);
01326 
01327     if (transport_type == TRANSPORT_ROAD) {
01328       RoadTypes rts = GetRoadTypes(ti->tile);
01329 
01330       if (HasBit(rts, ROADTYPE_TRAM)) {
01331         uint offset = tunnelbridge_direction;
01332         uint z = ti->z;
01333         if (ti->tileh != SLOPE_FLAT) {
01334           offset = (offset + 1) & 1;
01335           z += TILE_HEIGHT;
01336         } else {
01337           offset += 2;
01338         }
01339         /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01340         DrawBridgeTramBits(ti->x, ti->y, z, offset, HasBit(rts, ROADTYPE_ROAD), true);
01341       }
01342       EndSpriteCombine();
01343     } else if (transport_type == TRANSPORT_RAIL) {
01344       const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(ti->tile));
01345       if (rti->UsesOverlay()) {
01346         SpriteID surface = GetCustomRailSprite(rti, ti->tile, RTSG_BRIDGE);
01347         if (surface != 0) {
01348           if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
01349             AddSortableSpriteToDraw(surface + ((DiagDirToAxis(tunnelbridge_direction) == AXIS_X) ? RTBO_X : RTBO_Y), PAL_NONE, ti->x, ti->y, 16, 16, 0, ti->z + 8);
01350           } else {
01351             AddSortableSpriteToDraw(surface + RTBO_SLOPE + tunnelbridge_direction, PAL_NONE, ti->x, ti->y, 16, 16, 8, ti->z);
01352           }
01353         }
01354         /* Don't fallback to non-overlay sprite -- the spec states that
01355          * if an overlay is present then the bridge surface must be
01356          * present. */
01357       } else if (_game_mode != GM_MENU &&_settings_client.gui.show_track_reservation && HasTunnelBridgeReservation(ti->tile)) {
01358         if (HasBridgeFlatRamp(ti->tileh, DiagDirToAxis(tunnelbridge_direction))) {
01359           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);
01360         } else {
01361           AddSortableSpriteToDraw(rti->base_sprites.single_sloped + tunnelbridge_direction, PALETTE_CRASH, ti->x, ti->y, 16, 16, 8, ti->z);
01362         }
01363       }
01364       EndSpriteCombine();
01365       if (HasCatenaryDrawn(GetRailType(ti->tile))) {
01366         DrawCatenary(ti);
01367       }
01368     }
01369     /*Draw signals for bridge*/
01370     if (HasWormholeSignals(ti->tile)) DrawTunnelBridgeRampSignal(ti);
01371 
01372     DrawBridgeMiddle(ti);
01373   }
01374 }
01375 
01394 static BridgePieces CalcBridgePiece(uint north, uint south)
01395 {
01396   if (north == 1) {
01397     return BRIDGE_PIECE_NORTH;
01398   } else if (south == 1) {
01399     return BRIDGE_PIECE_SOUTH;
01400   } else if (north < south) {
01401     return north & 1 ? BRIDGE_PIECE_INNER_SOUTH : BRIDGE_PIECE_INNER_NORTH;
01402   } else if (north > south) {
01403     return south & 1 ? BRIDGE_PIECE_INNER_NORTH : BRIDGE_PIECE_INNER_SOUTH;
01404   } else {
01405     return north & 1 ? BRIDGE_PIECE_MIDDLE_EVEN : BRIDGE_PIECE_MIDDLE_ODD;
01406   }
01407 }
01408 
01413 void DrawBridgeMiddle(const TileInfo *ti)
01414 {
01415   /* Sectional view of bridge bounding boxes:
01416    *
01417    *  1           2                                1,2 = SpriteCombine of Bridge front/(back&floor) and TramCatenary
01418    *  1           2                                  3 = empty helper BB
01419    *  1     7     2                                4,5 = pillars under higher bridges
01420    *  1 6 88888 6 2                                  6 = elrail-pylons
01421    *  1 6 88888 6 2                                  7 = elrail-wire
01422    *  1 6 88888 6 2  <- TILE_HEIGHT                  8 = rail-vehicle on bridge
01423    *  3333333333333  <- BB_Z_SEPARATOR
01424    *                 <- unused
01425    *    4       5    <- BB_HEIGHT_UNDER_BRIDGE
01426    *    4       5
01427    *    4       5
01428    *
01429    */
01430 
01431   if (!IsBridgeAbove(ti->tile)) return;
01432 
01433   TileIndex rampnorth = GetNorthernBridgeEnd(ti->tile);
01434   TileIndex rampsouth = GetSouthernBridgeEnd(ti->tile);
01435   TransportType transport_type = GetTunnelBridgeTransportType(rampsouth);
01436 
01437   Axis axis = GetBridgeAxis(ti->tile);
01438   BridgePieces piece = CalcBridgePiece(
01439     GetTunnelBridgeLength(ti->tile, rampnorth) + 1,
01440     GetTunnelBridgeLength(ti->tile, rampsouth) + 1
01441   );
01442 
01443   const PalSpriteID *psid;
01444   bool drawfarpillar;
01445   if (transport_type != TRANSPORT_WATER) {
01446     BridgeType type =  GetBridgeType(rampsouth);
01447     drawfarpillar = !HasBit(GetBridgeSpec(type)->flags, 0);
01448 
01449     uint base_offset;
01450     if (transport_type == TRANSPORT_RAIL) {
01451       base_offset = GetRailTypeInfo(GetRailType(rampsouth))->bridge_offset;
01452     } else {
01453       base_offset = 8;
01454     }
01455 
01456     psid = base_offset + GetBridgeSpriteTable(type, piece);
01457   } else {
01458     drawfarpillar = true;
01459     psid = _aqueduct_sprites;
01460   }
01461 
01462   if (axis != AXIS_X) psid += 4;
01463 
01464   int x = ti->x;
01465   int y = ti->y;
01466   uint bridge_z = GetBridgeHeight(rampsouth);
01467   uint z = bridge_z - BRIDGE_Z_START;
01468 
01469   /* Add a bounding box that separates the bridge from things below it. */
01470   AddSortableSpriteToDraw(SPR_EMPTY_BOUNDING_BOX, PAL_NONE, x, y, 16, 16, 1, bridge_z - TILE_HEIGHT + BB_Z_SEPARATOR);
01471 
01472   /* Draw Trambits as SpriteCombine */
01473   if (transport_type == TRANSPORT_ROAD || transport_type == TRANSPORT_RAIL) StartSpriteCombine();
01474 
01475   /* Draw floor and far part of bridge*/
01476   if (!IsInvisibilitySet(TO_BRIDGES)) {
01477     if (axis == AXIS_X) {
01478       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 1, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01479     } else {
01480       AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 1, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 0, BRIDGE_Z_START);
01481     }
01482   }
01483 
01484   psid++;
01485 
01486   if (transport_type == TRANSPORT_ROAD) {
01487     RoadTypes rts = GetRoadTypes(rampsouth);
01488 
01489     if (HasBit(rts, ROADTYPE_TRAM)) {
01490       /* DrawBridgeTramBits() calls EndSpriteCombine() and StartSpriteCombine() */
01491       DrawBridgeTramBits(x, y, bridge_z, axis ^ 1, HasBit(rts, ROADTYPE_ROAD), false);
01492     } else {
01493       EndSpriteCombine();
01494       StartSpriteCombine();
01495     }
01496   } else if (transport_type == TRANSPORT_RAIL) {
01497     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(rampsouth));
01498     if (rti->UsesOverlay()) {
01499       SpriteID surface = GetCustomRailSprite(rti, rampsouth, RTSG_BRIDGE, TCX_ON_BRIDGE);
01500       if (surface != 0) {
01501         AddSortableSpriteToDraw(surface + axis, PAL_NONE, x, y, 16, 16, 0, bridge_z, IsTransparencySet(TO_BRIDGES));
01502       }
01503     }
01504     EndSpriteCombine();
01505 
01506     if (HasCatenaryDrawn(GetRailType(rampsouth))) {
01507       DrawCatenaryOnBridge(ti);
01508     }
01509 
01510     if (HasWormholeSignals(rampsouth)) {
01511       IsTunnelBridgeExit(rampsouth) ? DrawBrigeSignalOnMiddelPart(ti, rampnorth, z): DrawBrigeSignalOnMiddelPart(ti, rampsouth, z);
01512     }
01513   }
01514 
01515   /* draw roof, the component of the bridge which is logically between the vehicle and the camera */
01516   if (!IsInvisibilitySet(TO_BRIDGES)) {
01517     if (axis == AXIS_X) {
01518       y += 12;
01519       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 16, 4, 0x28, z, IsTransparencySet(TO_BRIDGES), 0, 3, BRIDGE_Z_START);
01520     } else {
01521       x += 12;
01522       if (psid->sprite & SPRITE_MASK) AddSortableSpriteToDraw(psid->sprite, psid->pal, x, y, 4, 16, 0x28, z, IsTransparencySet(TO_BRIDGES), 3, 0, BRIDGE_Z_START);
01523     }
01524   }
01525 
01526   /* Draw TramFront as SpriteCombine */
01527   if (transport_type == TRANSPORT_ROAD) EndSpriteCombine();
01528 
01529   /* Do not draw anything more if bridges are invisible */
01530   if (IsInvisibilitySet(TO_BRIDGES)) return;
01531 
01532   psid++;
01533   if (ti->z + 5 == z) {
01534     /* draw poles below for small bridges */
01535     if (psid->sprite != 0) {
01536       SpriteID image = psid->sprite;
01537       SpriteID pal   = psid->pal;
01538       if (IsTransparencySet(TO_BRIDGES)) {
01539         SetBit(image, PALETTE_MODIFIER_TRANSPARENT);
01540         pal = PALETTE_TO_TRANSPARENT;
01541       }
01542 
01543       DrawGroundSpriteAt(image, pal, x - ti->x, y - ti->y, z - ti->z);
01544     }
01545   } else if (_settings_client.gui.bridge_pillars) {
01546     /* draw pillars below for high bridges */
01547     DrawBridgePillars(psid, ti, axis, drawfarpillar, x, y, z);
01548   }
01549 }
01550 
01551 
01552 static uint GetSlopeZ_TunnelBridge(TileIndex tile, uint x, uint y)
01553 {
01554   uint z;
01555   Slope tileh = GetTileSlope(tile, &z);
01556 
01557   x &= 0xF;
01558   y &= 0xF;
01559 
01560   if (IsTunnel(tile)) {
01561     uint pos = (DiagDirToAxis(GetTunnelBridgeDirection(tile)) == AXIS_X ? y : x);
01562 
01563     /* In the tunnel entrance? */
01564     if (5 <= pos && pos <= 10) return z;
01565   } else { // IsBridge(tile)
01566     DiagDirection dir = GetTunnelBridgeDirection(tile);
01567     uint pos = (DiagDirToAxis(dir) == AXIS_X ? y : x);
01568 
01569     z += ApplyFoundationToSlope(GetBridgeFoundation(tileh, DiagDirToAxis(dir)), &tileh);
01570 
01571     /* On the bridge ramp? */
01572     if (5 <= pos && pos <= 10) {
01573       uint delta;
01574 
01575       if (tileh != SLOPE_FLAT) return z + TILE_HEIGHT;
01576 
01577       switch (dir) {
01578         default: NOT_REACHED();
01579         case DIAGDIR_NE: delta = (TILE_SIZE - 1 - x) / 2; break;
01580         case DIAGDIR_SE: delta = y / 2; break;
01581         case DIAGDIR_SW: delta = x / 2; break;
01582         case DIAGDIR_NW: delta = (TILE_SIZE - 1 - y) / 2; break;
01583       }
01584       return z + 1 + delta;
01585     }
01586   }
01587 
01588   return z + GetPartialZ(x, y, tileh);
01589 }
01590 
01591 static Foundation GetFoundation_TunnelBridge(TileIndex tile, Slope tileh)
01592 {
01593   return IsTunnel(tile) ? FOUNDATION_NONE : GetBridgeFoundation(tileh, DiagDirToAxis(GetTunnelBridgeDirection(tile)));
01594 }
01595 
01596 static void GetTileDesc_TunnelBridge(TileIndex tile, TileDesc *td)
01597 {
01598   TransportType tt = GetTunnelBridgeTransportType(tile);
01599 
01600   if (IsTunnel(tile)) {
01601     td->str = (tt == TRANSPORT_RAIL) ? HasWormholeSignals(tile) ? STR_LAI_TUNNEL_DESCRIPTION_RAILROAD_SIGNAL : STR_LAI_TUNNEL_DESCRIPTION_RAILROAD : STR_LAI_TUNNEL_DESCRIPTION_ROAD;
01602   } else { // IsBridge(tile)
01603     td->str = (tt == TRANSPORT_WATER) ? STR_LAI_BRIDGE_DESCRIPTION_AQUEDUCT : HasWormholeSignals(tile) ? STR_LAI_BRIDGE_DESCRIPTION_RAILROAD_SIGNAL : GetBridgeSpec(GetBridgeType(tile))->transport_name[tt];
01604   }
01605   td->owner[0] = GetTileOwner(tile);
01606 
01607   Owner road_owner = INVALID_OWNER;
01608   Owner tram_owner = INVALID_OWNER;
01609   RoadTypes rts = GetRoadTypes(tile);
01610   if (HasBit(rts, ROADTYPE_ROAD)) road_owner = GetRoadOwner(tile, ROADTYPE_ROAD);
01611   if (HasBit(rts, ROADTYPE_TRAM)) tram_owner = GetRoadOwner(tile, ROADTYPE_TRAM);
01612 
01613   /* Is there a mix of owners? */
01614   if ((tram_owner != INVALID_OWNER && tram_owner != td->owner[0]) ||
01615       (road_owner != INVALID_OWNER && road_owner != td->owner[0])) {
01616     uint i = 1;
01617     if (road_owner != INVALID_OWNER) {
01618       td->owner_type[i] = STR_LAND_AREA_INFORMATION_ROAD_OWNER;
01619       td->owner[i] = road_owner;
01620       i++;
01621     }
01622     if (tram_owner != INVALID_OWNER) {
01623       td->owner_type[i] = STR_LAND_AREA_INFORMATION_TRAM_OWNER;
01624       td->owner[i] = tram_owner;
01625     }
01626   }
01627 
01628   if (tt == TRANSPORT_RAIL) {
01629     const RailtypeInfo *rti = GetRailTypeInfo(GetRailType(tile));
01630     td->rail_speed = rti->max_speed;
01631 
01632     if (!IsTunnel(tile)) {
01633       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01634       if (td->rail_speed == 0 || spd < td->rail_speed) {
01635         td->rail_speed = spd;
01636       }
01637     }
01638   }
01639 }
01640 
01641 
01642 static void TileLoop_TunnelBridge(TileIndex tile)
01643 {
01644   bool snow_or_desert = HasTunnelBridgeSnowOrDesert(tile);
01645   switch (_settings_game.game_creation.landscape) {
01646     case LT_ARCTIC: {
01647       /* As long as we do not have a snow density, we want to use the density
01648        * from the entry endge. For tunnels this is the lowest point for bridges the highest point.
01649        * (Independent of foundations) */
01650       uint z = IsBridge(tile) ? GetTileMaxZ(tile) : GetTileZ(tile);
01651       if (snow_or_desert != (z > GetSnowLine())) {
01652         SetTunnelBridgeSnowOrDesert(tile, !snow_or_desert);
01653         MarkTileDirtyByTile(tile);
01654       }
01655       break;
01656     }
01657 
01658     case LT_TROPIC:
01659       if (GetTropicZone(tile) == TROPICZONE_DESERT && !snow_or_desert) {
01660         SetTunnelBridgeSnowOrDesert(tile, true);
01661         MarkTileDirtyByTile(tile);
01662       }
01663       break;
01664 
01665     default:
01666       break;
01667   }
01668 }
01669 
01670 static bool ClickTile_TunnelBridge(TileIndex tile)
01671 {
01672   /* Show vehicles found in tunnel */
01673   if (IsTunnelTile(tile)) {
01674     int count = 0;
01675     const Train *t;
01676     TileIndex tile_end = GetOtherTunnelBridgeEnd(tile);
01677     FOR_ALL_TRAINS(t) {
01678       if (!t->IsFrontEngine()) continue;
01679       if (tile == t->tile || tile_end == t->tile) {
01680         ShowVehicleViewWindow(t);
01681         count++;
01682       }
01683       if (count > 19) break;  // no more than 20 windows open
01684     }
01685     if (count > 0) return true;
01686   }
01687   return false;
01688 }
01689 
01690 static TrackStatus GetTileTrackStatus_TunnelBridge(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
01691 {
01692   TransportType transport_type = GetTunnelBridgeTransportType(tile);
01693   if (transport_type != mode || (transport_type == TRANSPORT_ROAD && (GetRoadTypes(tile) & sub_mode) == 0)) return 0;
01694 
01695   DiagDirection dir = GetTunnelBridgeDirection(tile);
01696   if (side != INVALID_DIAGDIR && side != ReverseDiagDir(dir)) return 0;
01697   return CombineTrackStatus(TrackBitsToTrackdirBits(DiagDirToDiagTrackBits(dir)), TRACKDIR_BIT_NONE);
01698 }
01699 
01700 static void ChangeTileOwner_TunnelBridge(TileIndex tile, Owner old_owner, Owner new_owner)
01701 {
01702   for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01703     /* Update all roadtypes, no matter if they are present */
01704     if (GetRoadOwner(tile, rt) == old_owner) {
01705       SetRoadOwner(tile, rt, new_owner == INVALID_OWNER ? OWNER_NONE : new_owner);
01706     }
01707   }
01708 
01709   if (!IsTileOwner(tile, old_owner)) return;
01710 
01711   if (new_owner != INVALID_OWNER) {
01712     SetTileOwner(tile, new_owner);
01713   } else {
01714     if (GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL) {
01715       /* Since all of our vehicles have been removed, it is safe to remove the rail
01716        * bridge / tunnel. */
01717       CommandCost ret = DoCommand(tile, 0, 0, DC_EXEC | DC_BANKRUPT, CMD_LANDSCAPE_CLEAR);
01718       assert(ret.Succeeded());
01719     } else {
01720       /* In any other case, we can safely reassign the ownership to OWNER_NONE. */
01721       SetTileOwner(tile, OWNER_NONE);
01722     }
01723   }
01724 }
01725 
01731 static const byte TUNNEL_SOUND_FRAME = 1;
01732 
01741 extern const byte _tunnel_visibility_frame[DIAGDIR_END] = {12, 8, 8, 12};
01742 
01743 static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
01744 {
01745   int z = GetSlopeZ(x, y) - v->z_pos;
01746 
01747   if (abs(z) > 2) return VETSB_CANNOT_ENTER;
01748   /* Direction into the wormhole */
01749   const DiagDirection dir = GetTunnelBridgeDirection(tile);
01750   /* Direction of the vehicle */
01751   const DiagDirection vdir = DirToDiagDir(v->direction);
01752   /* New position of the vehicle on the tile */
01753   byte pos = (DiagDirToAxis(vdir) == AXIS_X ? x : y) & TILE_UNIT_MASK;
01754   /* Number of units moved by the vehicle since entering the tile */
01755   byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
01756 
01757   if (IsTunnel(tile)) {
01758     if (v->type == VEH_TRAIN) {
01759       Train *t = Train::From(v);
01760 
01761       if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
01762         if (t->IsFrontEngine() && frame == TUNNEL_SOUND_FRAME) {
01763           if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
01764             SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
01765           }
01766           return VETSB_CONTINUE;
01767         }
01768         if (frame == _tunnel_visibility_frame[dir]) {
01769           t->tile = tile;
01770           t->track = TRACK_BIT_WORMHOLE;
01771           t->vehstatus |= VS_HIDDEN;
01772           return VETSB_ENTERED_WORMHOLE;
01773         }
01774       }
01775 
01776       if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
01777         /* We're at the tunnel exit ?? */
01778         t->tile = tile;
01779         t->track = DiagDirToDiagTrackBits(vdir);
01780         assert(t->track);
01781         t->vehstatus &= ~VS_HIDDEN;
01782         return VETSB_ENTERED_WORMHOLE;
01783       }
01784     } else if (v->type == VEH_ROAD) {
01785       RoadVehicle *rv = RoadVehicle::From(v);
01786 
01787       /* Enter tunnel? */
01788       if (rv->state != RVSB_WORMHOLE && dir == vdir) {
01789         if (frame == _tunnel_visibility_frame[dir]) {
01790           /* Frame should be equal to the next frame number in the RV's movement */
01791           assert(frame == rv->frame + 1);
01792           rv->tile = tile;
01793           rv->state = RVSB_WORMHOLE;
01794           rv->vehstatus |= VS_HIDDEN;
01795           return VETSB_ENTERED_WORMHOLE;
01796         } else {
01797           return VETSB_CONTINUE;
01798         }
01799       }
01800 
01801       /* We're at the tunnel exit ?? */
01802       if (dir == ReverseDiagDir(vdir) && frame == TILE_SIZE - _tunnel_visibility_frame[dir] && z == 0) {
01803         rv->tile = tile;
01804         rv->state = DiagDirToDiagTrackdir(vdir);
01805         rv->frame = frame;
01806         rv->vehstatus &= ~VS_HIDDEN;
01807         return VETSB_ENTERED_WORMHOLE;
01808       }
01809     }
01810   } else { // IsBridge(tile)
01811     if (v->type != VEH_SHIP) {
01812       /* modify speed of vehicle */
01813       uint16 spd = GetBridgeSpec(GetBridgeType(tile))->speed;
01814 
01815       if (v->type == VEH_ROAD) spd *= 2;
01816       Vehicle *first = v->First();
01817       first->cur_speed = min(first->cur_speed, spd);
01818     }
01819 
01820     if (vdir == dir) {
01821       /* Vehicle enters bridge at the last frame inside this tile. */
01822       if (frame != TILE_SIZE - 1) return VETSB_CONTINUE;
01823       switch (v->type) {
01824         case VEH_TRAIN: {
01825           Train *t = Train::From(v);
01826           t->track = TRACK_BIT_WORMHOLE;
01827           ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
01828           ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
01829           break;
01830         }
01831 
01832         case VEH_ROAD: {
01833           RoadVehicle *rv = RoadVehicle::From(v);
01834           rv->state = RVSB_WORMHOLE;
01835           /* There are no slopes inside bridges / tunnels. */
01836           ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
01837           ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
01838           break;
01839         }
01840 
01841         case VEH_SHIP:
01842           Ship::From(v)->state = TRACK_BIT_WORMHOLE;
01843           break;
01844 
01845         default: NOT_REACHED();
01846       }
01847       return VETSB_ENTERED_WORMHOLE;
01848     } else if (vdir == ReverseDiagDir(dir)) {
01849       v->tile = tile;
01850       switch (v->type) {
01851         case VEH_TRAIN: {
01852           Train *t = Train::From(v);
01853           if (t->track == TRACK_BIT_WORMHOLE) {
01854             t->track = DiagDirToDiagTrackBits(vdir);
01855             return VETSB_ENTERED_WORMHOLE;
01856           }
01857           break;
01858         }
01859 
01860         case VEH_ROAD: {
01861           RoadVehicle *rv = RoadVehicle::From(v);
01862           if (rv->state == RVSB_WORMHOLE) {
01863             rv->state = DiagDirToDiagTrackdir(vdir);
01864             rv->frame = 0;
01865             return VETSB_ENTERED_WORMHOLE;
01866           }
01867           break;
01868         }
01869 
01870         case VEH_SHIP: {
01871           Ship *ship = Ship::From(v);
01872           if (ship->state == TRACK_BIT_WORMHOLE) {
01873             ship->state = DiagDirToDiagTrackBits(vdir);
01874             return VETSB_ENTERED_WORMHOLE;
01875           }
01876           break;
01877         }
01878 
01879         default: NOT_REACHED();
01880       }
01881     }
01882   }
01883   return VETSB_CONTINUE;
01884 }
01885 
01886 static CommandCost TerraformTile_TunnelBridge(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
01887 {
01888   if (_settings_game.construction.build_on_slopes && AutoslopeEnabled() && IsBridge(tile) && GetTunnelBridgeTransportType(tile) != TRANSPORT_WATER) {
01889     DiagDirection direction = GetTunnelBridgeDirection(tile);
01890     Axis axis = DiagDirToAxis(direction);
01891     CommandCost res;
01892     uint z_old;
01893     Slope tileh_old = GetTileSlope(tile, &z_old);
01894 
01895     /* Check if new slope is valid for bridges in general (so we can safely call GetBridgeFoundation()) */
01896     if ((direction == DIAGDIR_NW) || (direction == DIAGDIR_NE)) {
01897       CheckBridgeSlopeSouth(axis, &tileh_old, &z_old);
01898       res = CheckBridgeSlopeSouth(axis, &tileh_new, &z_new);
01899     } else {
01900       CheckBridgeSlopeNorth(axis, &tileh_old, &z_old);
01901       res = CheckBridgeSlopeNorth(axis, &tileh_new, &z_new);
01902     }
01903 
01904     /* Surface slope is valid and remains unchanged? */
01905     if (res.Succeeded() && (z_old == z_new) && (tileh_old == tileh_new)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
01906   }
01907 
01908   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
01909 }
01910 
01911 extern const TileTypeProcs _tile_type_tunnelbridge_procs = {
01912   DrawTile_TunnelBridge,           // draw_tile_proc
01913   GetSlopeZ_TunnelBridge,          // get_slope_z_proc
01914   ClearTile_TunnelBridge,          // clear_tile_proc
01915   NULL,                            // add_accepted_cargo_proc
01916   GetTileDesc_TunnelBridge,        // get_tile_desc_proc
01917   GetTileTrackStatus_TunnelBridge, // get_tile_track_status_proc
01918   ClickTile_TunnelBridge,          // click_tile_proc
01919   NULL,                            // animate_tile_proc
01920   TileLoop_TunnelBridge,           // tile_loop_clear
01921   ChangeTileOwner_TunnelBridge,    // change_tile_owner_clear
01922   NULL,                            // add_produced_cargo_proc
01923   VehicleEnter_TunnelBridge,       // vehicle_enter_tile_proc
01924   GetFoundation_TunnelBridge,      // get_foundation_proc
01925   TerraformTile_TunnelBridge,      // terraform_tile_proc
01926 };