# tunnelbridge_cmd.cpp

Go to the documentation of this file.

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