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