tunnelbridge_cmd.cpp

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