# tunnelbridge_cmd.cpp

Go to the documentation of this file.

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