tunnelbridge_cmd.cpp

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

Generated on Thu Feb 4 17:20:30 2010 for OpenTTD by  doxygen 1.5.6